我需要加密一个字符串。最初的版本是用Java写的,现在需要用javascript重写。但我有不同的结果。 这是 java 中的代码:
Java 版本:
private static String getEncrypt(String input, String salt) throws NoSuchAlgorithmException {
byte[] raw_salt = Base64.getDecoder().decode(salt);
byte[] raw_data = input.getBytes(StandardCharsets.UTF_8);
byte[] test_data = new byte[raw_salt.length + raw_data.length];
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
System.arraycopy(raw_salt, 0, test_data, 0, raw_salt.length);
System.arraycopy(raw_data, 0, test_data, raw_salt.length, raw_data.length);
mdTemp.update(test_data);
byte[] bytes = mdTemp.digest();
return new String(Base64.getEncoder().encode(bytes));
}
input: 123456789
salt: pMm6kWsoWjR18sWKnoG4Az==
output: 6u/VAXS9ZKmLEbHw/OZ1AVarth4=
JS 版本:(使用 crypto.js)
const crypto = require("crypto");
function getEncrypt(input, salt){
const sha1 = crypto.createHash('sha1');
const beforeCrypto = salt + input;
const afterCrypto = sha1.update(beforeCrypto).digest('base64');
return afterCrypto;
}
input: 123456789
salt: pMm6kWsoWjR18sWKnoG4Az==
output: ie/3j+92nxvcNT5i+3WUJbWsEAg=
Java 中的MessageDigest
方法要求我以byte[]
格式输入。在javascript 中,我使用·string· 类型输入。
他们还使用 salt
来使加密更安全,但它带来了更多不同,我无法用 javascript 重写它。
我尝试了很多方法来解决它。但我仍然得不到相同的结果。
最佳答案
下面的片段也给了我正确的答案:
98O8HYCOBHMq32eZZczDTKeuNEE=
您的代码中一定有一些细节不同。 我做的一件事是使用 UTF8 标准字符集,以避免在指定“utf-8”与“UTF8”等方式时出现任何错误。
您的代码无法编译(例如,缺少 getEncrypt 的返回类型),因此可能存在其他不同之处。
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class Main {
private static String getEncrypt(String input) throws NoSuchAlgorithmException {
byte[] raw_data = input.getBytes(StandardCharsets.UTF_8);
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(raw_data);
byte[] bytes = mdTemp.digest();
return new String(Base64.getEncoder().encode(bytes));
}
public static void main(String[] args){
try {
System.out.println(getEncrypt("123456789"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
关于javascript - Crypto.js SHA1 与 MessageDigest java SHA1 : why different results?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56391280/