注意:MD5散列算法不应用于密码存储,因为它的哈希很容易被破解。但是出于简单起见,我将使用它。
快速/简便/不安全的解决方法是将字符数组转换为字符串。然而,这种方法不安全,因为字符串是不可变的,并且无法从内存中清除。
String password = new String(passwordInputField.getPassword());
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
String hashedPass = new BigInteger(1, md.digest()).toString(16);
一种更安全的解决方案:将char[]转换为byte[],然后清除数组中的数据。
private byte[] toBytes(char[] chars) {
CharBuffer charBuffer = CharBuffer.wrap(chars);
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
byteBuffer.position(), byteBuffer.limit());
Arrays.fill(charBuffer.array(), '\u0000');
Arrays.fill(byteBuffer.array(), (byte) 0);
return bytes;
}
char[] passChars = passwordInputField.getPassword();
byte[] passBytes = toBytes(passChars);
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(passBytes);
String hashedPass = new BigInteger(1, md.digest()).toString(16);
Arrays.fill(passChars, '\u0000');
Arrays.fill(passBytes, (byte) 0);
编辑:
更新了更安全的解决方案(感谢user2656928提供的想法)。
char[]转byte[]方法,由andreyne提供