提交 e0b6a07f authored 作者: Evgenij Ryazanov's avatar Evgenij Ryazanov

There is no need to normalize keys for HmacSHA256 except for empty keys

上级 1f4677bb
...@@ -78,7 +78,6 @@ public class SHA256 { ...@@ -78,7 +78,6 @@ public class SHA256 {
* @return the hash * @return the hash
*/ */
public static byte[] getHMAC(byte[] key, byte[] message) { public static byte[] getHMAC(byte[] key, byte[] message) {
key = normalizeKeyForHMAC(key);
Mac mac = initMac(key); Mac mac = initMac(key);
return calculateHMAC(mac, message, message.length); return calculateHMAC(mac, message, message.length);
} }
...@@ -88,17 +87,11 @@ public class SHA256 { ...@@ -88,17 +87,11 @@ public class SHA256 {
return mac.doFinal(); return mac.doFinal();
} }
private static byte[] normalizeKeyForHMAC(byte[] key) {
if (key.length > 64) {
key = getHash(key, false);
}
if (key.length < 64) {
key = Arrays.copyOf(key, 64);
}
return key;
}
private static Mac initMac(byte[] key) { private static Mac initMac(byte[] key) {
// Java forbids empty keys
if (key.length == 0) {
key = new byte[1];
}
try { try {
Mac mac = Mac.getInstance("HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256")); mac.init(new SecretKeySpec(key, "HmacSHA256"));
...@@ -120,8 +113,7 @@ public class SHA256 { ...@@ -120,8 +113,7 @@ public class SHA256 {
public static byte[] getPBKDF2(byte[] password, byte[] salt, public static byte[] getPBKDF2(byte[] password, byte[] salt,
int iterations, int resultLen) { int iterations, int resultLen) {
byte[] result = new byte[resultLen]; byte[] result = new byte[resultLen];
byte[] key = normalizeKeyForHMAC(password); Mac mac = initMac(password);
Mac mac = initMac(key);
int len = 64 + Math.max(32, salt.length + 4); int len = 64 + Math.max(32, salt.length + 4);
byte[] message = new byte[len]; byte[] message = new byte[len];
byte[] macRes = null; byte[] macRes = null;
...@@ -142,7 +134,6 @@ public class SHA256 { ...@@ -142,7 +134,6 @@ public class SHA256 {
} }
} }
Arrays.fill(password, (byte) 0); Arrays.fill(password, (byte) 0);
Arrays.fill(key, (byte) 0);
return result; return result;
} }
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论