gpt4 book ai didi

javascript - 从 Java 到 node.js 的 encryptAES

转载 作者:搜寻专家 更新时间:2023-10-31 23:20:15 27 4
gpt4 key购买 nike

我有一个AES加解密的Java算法,要用JavaScript实现解密。

 public static final String ENCRYPTION_ALGORITHM = "AES/CBC/PKCS5Padding";
public static String wrap(String clearText, String key) {
byte[] iv = getIv();

byte[] cipherText = encrypt(clearText, key, iv);
byte[] wrapped = new byte[iv.length + cipherText.length];
System.arraycopy(iv, 0, wrapped, 0, iv.length);
System.arraycopy(cipherText, 0, wrapped, 16, cipherText.length);

return new String(Base64.encodeBase64(wrapped));
}

private static byte[] encrypt(String clearText, String key, byte[] iv) {
try {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(iv));
cipher.init(Cipher.ENCRYPT_MODE, getKey(key), params);
return cipher.doFinal(clearText.getBytes());
} catch (GeneralSecurityException e) {
throw new RuntimeException("Failed to encrypt.", e);
}
}

private static SecretKeySpec getKey(String key) {
try {
return new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
} catch (DecoderException e) {
throw new RuntimeException("Failed to generate a secret key spec", e);
}
}

private static byte[] getIv() {
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);

return iv;
}

我写了 javascript 代码,但它生成了不正确的结果:

var responseBody = JSON.stringify({"key":"215467ryhfdjeu8373t4"});
var initializationVector = crypto.randomBytes(16);
key = new Buffer(key.substring(0,32), 'hex');
var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
var encrypted = cipher.update(new Buffer(responseBody)) + cipher.final('hex');
var encoded = new Buffer(initializationVector+encrypted, 'binary');
return encoded;

你能帮我把 Java wrap 函数重写成 javascript(NodeJS) 吗?

最佳答案

问题已解决。

问题出在缓冲区的连接上。运算符“+”对此不正确。需要使用默认方法。

Buffer.concat([initializationVector, encrypted])

关于javascript - 从 Java 到 node.js 的 encryptAES,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40903217/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com