secguide icon indicating copy to clipboard operation
secguide copied to clipboard

#java# 规范 错误的十六进制串联 增补修订建议

Open k4n5ha0 opened this issue 3 years ago • 0 comments

将包含哈希签名的字节数组转换为人类可读的字符串时,如果逐字节读取该数组,则可能会发生转换错误。 所有对于数据格式化的操作应优先使用规范的数据格式化处理机制。

脆弱代码:

MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] resultBytes = md.digest(password.getBytes("UTF-8"));

StringBuilder stringBuilder = new StringBuilder();
for(byte b :resultBytes) {
	stringBuilder.append( Integer.toHexString( b & 0xFF ) );
}
return stringBuilder.toString();

对于上述功能,哈希值 “0x0679” 和 “0x6709” 都将输出为 “679”

解决方案:

stringBuilder.append(String.format("%02X", b));

k4n5ha0 avatar May 24 '21 17:05 k4n5ha0