Groppe
Groppe

Reputation: 3879

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

Upvotes: 4

Views: 4146

Answers (1)

Adam
Adam

Reputation: 44959

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 = 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

Upvotes: 5

Related Questions