Different in Java SHA1 vs JavaScript SHA1

佐手、 提交于 2019-12-04 15:49:05

Here's the solution:

Javascript:

key = 'testKey';
var hashedKey = CryptoJS.SHA1(key);
console.log(hashedKey);

Output: 2420e186fcdb8d0ea08d82fdfbfb8722d6cbf606

Java:

password="testKey";
final MessageDigest md = MessageDigest.getInstance("SHA1");
ByteArrayOutputStream pwsalt = new ByteArrayOutputStream();
pwsalt.write(password.getBytes("UTF-8"));
byte[] unhashedBytes = pwsalt.toByteArray();
byte[] digestVonPassword = md.digest(unhashedBytes);
System.out.println(bytesToHex(digestVonPassword));

Output: 2420E186FCDB8D0EA08D82FDFBFB8722D6CBF606

With the exceptions of capital vs. lowercase, the output is the same. It's in hex, by the way.

Paul S.

In your JavaScript you're doing a SHA-1 on a String which is the numbers from a byte Array (so is different to your String content).

console.warn(CryptoJS.SHA1(content.getBytes().toString()).toString().getBytes());
//                                              ^^

In your Java, you're doing a SHA-1 on a byte[] (which is equivalent to your String content)

byte[] sha1 = MessageDigest.getInstance("SHA1").digest(message.getBytes());
//                                                                ^^

Your toString is creating a very different piece of data to what you're SHA-1-ing in Java.

Also (not sure if relevant): internally, JavaScript uses UTF-16 for Strings.


Further, the logged output of your JavaScript cannot be a SHA-1 as it is the wrong length; this is due to .toString().getBytes() repeated on the sha1 after it's been calculated (Stephen C mentions this in this comment).

I found this library. It produces same values as Java

https://caligatio.github.io/jsSHA/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!