我看过AES - Encryption with Crypto (node-js) / decryption with Pycrypto (python)帖子,因为我试图完全相反,但我似乎无法做到正确。这是我到目前为止所尝试的......
Python加密
import base64
from Crypto import Random
from Crypto.Cipher import AES
text_file = open("cryptic.txt", "w")
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[:-ord(s[len(s)-1:])]
plaintxt = 'dolladollabillzz'
iv = Random.new().read( AES.block_size )
print AES.block_size
key = 'totallyasecret!!'
cipher = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
encrypted = base64.b64encode(iv + cipher.encrypt(plaintxt))
text_file.write(encrypted)
text_file.close()
Node.js解密
var fs = require('fs');
var crypto = require('crypto');
var Buffer = require('buffer').Buffer;
var algorithm = 'aes-128-cbc';
var key = new Buffer('totallyasecret!!', 'binary');
var cryptic = fs.readFileSync('./cryptic.txt', 'base64');
var iv = cryptic.slice(0, 16);
var ciphertext = cryptic.slice(16);
var decipher = crypto.createDecipheriv(algorithm, key, iv);
var decrypted = [decipher.update(ciphertext)];
decrypted.push(decipher.final('utf8'));
var finished = Buffer.concat(decrypted).toString('utf8');
console.log(finished);
每次我尝试运行Node.js解密时,我都会收到错误消息:
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
答案 0 :(得分:0)
由于IV是在Python中随机生成的,因此它可以包含任何可能的字节值。其中一些字节值不是有效的UTF-8字符(例如,多个字节是一个字符),并且可能导致错误地切掉IV,因此实际的密文会稍微移位。
由于AES是分组密码,因此必须排队才能正确解密。这应该解决它:
var cryptic = fs.readFileSync('./cryptic.txt', 'utf8');
cryptic = new Buffer(cryptic, 'base64');
var iv = cryptic.slice(0, 16);
var ciphertext = cryptic.slice(16);
这会将二进制字符串更改为完全处理二进制数据的Buffer。