从 nodejs 加密和 Java 加密产生相同的结果

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);
}

但是,加密(“arellano”)returns“5b1AU5TWOa8g0HI2S1fsfA==”

如何调整 Java 代码以获得 NodeJS 给我的字符串?

  1. 这两个字符串肯定是“等价的”。我不需要检查。
  2. 问题是:我的 java 代码需要更改什么才能产生相同的结果?

正确答案是:使用这行代码:

    return String.format("%040x", new BigInteger(1, cipherText));

而不是:

    return Base64.getEncoder().encodeToString(cipherText);

就是这样。

感谢大家的帮助。