Groppe Groppe - 1 year ago 116
Java Question

Securely decoding a Base64 character array in Java

I need to decode a Base64 char array without converting it to a String. The char array is a password, and for security reasons I am not allowed to convert it to a String (this requirement is non-negotiable).

The java.util.Base64.Decoder.decode method accepts

, ByteBuffer, and String, but not

Security concerns of using a String to store sensitive data

per Jim Archer's comment

  • Strings are immutable

  • They can only be purged from memory by the Garbage Collector (which cannot be forced to do it)

Answer Source

Create a CharBuffer backed by the char[]. Then use Charset.encode to encode the byte buffer into a ByteBuffer. A ByteBuffer is accepted by the Base64 Decoder.

private static final java.util.Base64.Decoder BASE_64_DECODER= new java.util.Base64.Decoder();

private static final String ENCODING = "UTF-8";// Use the correct encoding here.

private byte[] decodePassword(char[] password) {
    CharBuffer charBuffer = CharBuffer.wrap(password);
    ByteBuffer byteBuffer = Charset.forName(ENCODING).encode(charBuffer);
    return BASE_64_DECODER.decode(byteBuffer);

Inspired by azurefox's comment and the answer here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download