英文:
Produce the same result from nodejs encryption and Java encryption
问题
以下是您要求的翻译内容:
在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);
现在,在Java中,我有这个方法:
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, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
return Base64.getEncoder().encodeToString(cipherText);
}
但是,encrypt("arellano") 返回 "5b1AU5TWOa8g0HI2S1fsfA=="
我该如何调整Java代码才能获得与NodeJS给我的字符串相同的结果?
英文:
In NodeJS this code produces this output: '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)
Now, in Java, I have this method:
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, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
return Base64.getEncoder().encodeToString(cipherText);
}
But, encrypt("arellano") returns "5b1AU5TWOa8g0HI2S1fsfA=="
How can I adjust the Java code for me to obtain the string that NodeJS is giving me?
答案1
得分: 0
- 两个字符串肯定是“等价的”。我不需要检查这一点。
- 问题是:我需要在我的 Java 代码中做哪些更改才能得到相同的结果?
正确的答案是:使用这行代码:
return String.format("%040x", new BigInteger(1, cipherText));
而不是:
return Base64.getEncoder().encodeToString(cipherText);
就是这样。
感谢大家的帮助。
英文:
- Both Strings are "equivalent" for sure. I do not need to check that.
- The question was: What do I need to change in my java code to produce the same result?.
The right answer is: Use this line of code:
return String.format("%040x", new BigInteger(1, cipherText));
Instead of:
return Base64.getEncoder().encodeToString(cipherText);
That's it.
Thanks everyone for your help.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论