在 Java 中安全解码 Base64 字符数组

Securely decoding a Base64 character array in Java

我需要解码 Base64 char array without converting it to a String。 char数组是一个密码,出于安全原因我不允许将其转换为String(这个要求是不可协商的)。

java.util.Base64.Decoder.decode method accepts byte[], ByteBuffer, and String,但不是char[]

使用字符串存储敏感数据的安全问题

根据 Jim Archer 的评论

创建 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);
}

受 azurefox 的评论和此处答案的启发: