Search code examples
javasecuritycharbase64decode

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 byte[], ByteBuffer, and String, but not char[].

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)

Solution

  • 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.getDecoder(); // Initializes a Decoder instance with getDecoder() method
    
    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: https://stackoverflow.com/a/9670279/1361506