用char []生成MD5哈希

豌豆Ghapantsyan

如何转换使用此方法获得的char []密码:

char[] password = passwordInputField.getPassword();

到MD5哈希?通常,我将使用以下方法,但getBytes仅与字符串兼容:

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
String hashedPass = new BigInteger(1, md.digest()).toString(16);
康纳

注意:请勿将MD5哈希算法用于密码存储,因为它的哈希很容易破解。但是,为了简单起见,我将使用它。

快速/简便/不安全的解决方法是将char数组转换为字符串。但是,这是不安全的,因为字符串是不可变的,无法从内存中清除。

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'); // clear sensitive data
    Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
    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'); // clear sensitive data
Arrays.fill(passBytes, (byte) 0); // clear sensitive data

编辑:

更新了答案,提供了更安全的解决方案(该想法归功于user2656928)。

char []到byte []方法归功于andreyne

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章