gpt4 book ai didi

javascript - Java中的AES加密无法在Javascript中解密

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:42 25 4
gpt4 key购买 nike

我使用 AES-256 (AES/CBC/PKCS5Padding) 基于密码的加密 (PBKDF2WithHmacSHA1)。

在Java中,我使用以下加密和解密代码并且工作正常。

String password = "MyPassword1";
String salt = "MysaltString"; //Will switch to random salt generation.
String plainText = "Quick Brown Fox";


SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 1024, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

/* Encrypt the message. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal(plainText.getBytes("UTF-8"));

/* Decrypt the message, given derived key and initialization vector. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(ciphertext), "UTF-8");

现在,为了实现互操作,我需要在 Javascript 中对加密字符串进行解密。我尝试使用 forge ( https://github.com/digitalbazaar/forge ) 但无法解密。

var password = "MyPassword1";
var salt = "MysaltString"; //Will switch to random salt generation.

var derivedKey = forge.pkcs5.pbkdf2(password, salt, 1024, 32);
input = forge.util.createBuffer(encrypted);
var decipher = forge.cipher.createDecipher('AES-CBC', derivedKey);
decipher.start({iv: iv});
decipher.update(input);
res = decipher.finish();

我的猜测是它与提供给 JS 的输入格式(密码、盐、IV、encrptedtext)有关,我只是无法弄清楚它是否必须是 base64、十六进制等......

最佳答案

原因是Java使用有符号字节。您应该在 IV 和密文的 JavaScript 端使用二进制补码。您的 JS 代码应如下所示:

var password = "MyPassword1";
var salt = "MysaltString";
var derivedKey = forge.pkcs5.pbkdf2(password, salt, 1024, 32);

for (var i = 0; i < iv_in.length; i++) {
iv_in[i] = (iv_in[i] & 0xFF);
}

var iv = String.fromCharCode.apply(String, iv_in);

for (var i = 0; i < encrypted.length; i++) {
encrypted[i] = (encrypted[i] & 0xFF);
}

var input_c = String.fromCharCode.apply(String, encrypted)

var input = forge.util.createBuffer(input_c);
var decipher = forge.cipher.createDecipher('AES-CBC', derivedKey);
decipher.start({iv: iv});
decipher.update(input);
var res = decipher.finish();

if (res) {
console.log(decipher.output.toString('utf8'));
}

其中 iv_inencrypted 是您从 Java 接收的输入字节数组,例如:

var iv_in = [24, -54, -15, 5, 106, -44, 20, 10, 103, -62, -88, 28, 75, -68, -12, -14];

var 加密 = [20, -56, 117, 80, -91, -104, 22, -43, -127, -87, 7, 113, 66, 85, 105, -25]

关于javascript - Java中的AES加密无法在Javascript中解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50679540/

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