问题描述
在NodeJS中,此代码产生以下输出:'e5bd405394d639af20d072364b57ec7c'
var key = 'gustavo'
var src = 'arellano'
var cipher = crypto.createCipher("aes-128-ecb",key)
var result = cipher.update(src).toString('hex');
result += cipher.final().toString('hex');
console.log(result)
private static String encrypt(String source) throws Exception {
byte[] input = source.getBytes(StandardCharsets.UTF_8);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest("gustavo".getBytes(StandardCharsets.UTF_8));
SecretKeySpec skc = new SecretKeySpec(thedigest,"AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,skc);
byte[] cipherText = new byte[cipher.getoutputSize(input.length)];
int ctLength = cipher.update(input,input.length,cipherText,0);
ctLength += cipher.doFinal(cipherText,ctLength);
return Base64.getEncoder().encodetoString(cipherText);
}
但是,encrypt(“ arellano”)返回“ 5b1AU5TWOa8g0HI2S1fsfA ==“
如何为我调整Java代码以获得NodeJS给我的字符串?
解决方法
- 两个字符串肯定是“等效的”。我不需要检查。
- 问题是:为了产生相同的结果,我需要在java代码中进行哪些更改?。
正确的答案是:使用以下代码行:
return String.format("%040x",new BigInteger(1,cipherText));
代替:
return Base64.getEncoder().encodeToString(cipherText);
就是这样。
感谢大家的帮助。