尝试使用使用SJCL的RNCryptor-js解密AES。记录每一端的所有步骤(另一端是RNCryptor-python)键,盐,HMAC哈希,一切都匹配。但是当我走到最后一步时:
var aes = new sjcl.cipher.aes(encryption_key);
sjcl.beware["CBC mode is dangerous because it doesn't protect message integrity."]()
var decrypted = aes.decrypt(ciphertext, iv);
我收到错误:
sjcl.exception.invalid {toString: function, message: "invalid aes block size"}
以下是完整代码:
PBKDF2:
this.KeyForPassword = function(password, salt) {
var hmacSHA256 = function (password) {
var hasher = new sjcl.misc.hmac(password, sjcl.hash.sha256);
this.encrypt = function () {
return hasher.encrypt.apply(hasher, arguments);
};
};
return sjcl.misc.pbkdf2(password, salt, 10000, 32 * 8, hmacSHA256);
};
解密(采用十六进制输入):
this.decrypt = function(password, message, options) {
message = sjcl.codec.hex.toBits(message);
options = options || {};
var version = sjcl.bitArray.extract(message, 0 * 8, 8);
var options = sjcl.bitArray.extract(message, 1 * 8, 8);
var encryption_salt = sjcl.bitArray.bitSlice(message, 2 * 8, 10 * 8);
var encryption_key = _this.KeyForPassword(password, encryption_salt, "decryption");
var hmac_salt = sjcl.bitArray.bitSlice(message, 10 * 8, 18 * 8);
var hmac_key = _this.KeyForPassword(password, hmac_salt, "decryption");
var iv = sjcl.bitArray.bitSlice(message, 18 * 8, 34 * 8);
var ciphertext_end = sjcl.bitArray.bitLength(message) - (32 * 8);
var ciphertext = sjcl.bitArray.bitSlice(message, 34 * 8, ciphertext_end);
var hmac = sjcl.bitArray.bitSlice(message, ciphertext_end);
var expected_hmac = new sjcl.misc.hmac(hmac_key).encrypt(sjcl.bitArray.bitSlice(message, 0, ciphertext_end));
if (! sjcl.bitArray.equal(hmac, expected_hmac)) {
throw new sjcl.exception.corrupt("HMAC mismatch or bad password.");
}
var aes = new sjcl.cipher.aes(encryption_key);
sjcl.beware["CBC mode is dangerous because it doesn't protect message integrity."]()
var decrypted = aes.decrypt(ciphertext, iv);
return decrypted;
}
在定义decrypted
的倒数第二个语句中抛出错误。
我查看了sjcl异常,看起来它正在寻找长度为4的输入,我猜测它是一个WordArray。我只是迷失了如何获得有效的输入。就像我说的那样,密文,iv,hmac标签,盐都在javascript端被正确切片。可能只是一个编码问题。
这个错误似乎也只发生在json上(格式:'{“key”:“value”}'),当我尝试“Hello,world”之类的东西时,我找回了一个没有错误的4字数组。
有什么建议吗?
答案 0 :(得分:0)
var decrypted = aes.decrypt(ciphertext, iv);
应该是
var decrypted = sjcl.mode.cbc.decrypt(aes, ciphertext, iv);
我在cbc.js
(link to source)发生填充时也遇到了问题,结果发现我没有包含bitArray.js
(link),其中包含一个重要的xor
函数(不要与简单的^
运算符混淆)。
所以:包括bitArray.js
输出也应编码:
return sjcl.codec.utf8String.fromBits(decrypted);