我正在尝试使用key =“secret_key”和文本“11869021012”加密字符串“1”。早些时候我在nodejs中写过这个。现在我想把它移植到python。但令人惊讶的是两者都给出了不同的产出。
var crypto = require('crypto');
function getBytes (str) {
let bytes = [], char;
str = encodeURI(str);
while (str.length) {
char = str.slice(0, 1);
str = str.slice(1);
if ('%' !== char) {
bytes.push(char.charCodeAt(0));
} else {
char = str.slice(0, 2);
str = str.slice(2);
bytes.push(parseInt(char, 16));
}
}
return bytes;
};
function getIV (str, bytes){
iv = getBytes(str);
if(!bytes) bytes = 16;
for(let i=iv.length;i<bytes;i++) {
iv.push(0);
}
return Buffer.from(iv);
};
function getKey (pwd){
pwd = Buffer.from(getBytes(pwd), 'utf-8');
let hash = crypto.createHash('sha256');
pwd = hash.update(pwd).digest();
return pwd;
};
function createCipherIV (algorithm, input_key, iv_input, text){
let iv = getIV(iv_input);
let key = getKey(input_key);
let cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text)
encrypted += cipher.final('base64');
return encrypted;
}
output = createCipherIV('aes256', 'secret_key', '11869021012', '1')
console.log(output)
这会产生输出:s6LMaE/YRT6y8vr2SehLKw==
python代码:
# AES 256 encryption/decryption using pycrypto library
import base64
import hashlib
from Crypto.Cipher import AES
from Crypto import Random
BLOCK_SIZE = 16
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
password = "secret_key"
def encrypt(raw, password):
private_key = hashlib.sha256(bytearray(password, "utf-8")).digest()
raw = pad(raw)
iv = b'11869021012\x00\x00\x00\x00\x00'
cleartext = bytearray(raw, 'utf-8')
cipher = AES.new(private_key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(cleartext))
# First let us encrypt secret message
encrypted = encrypt("1", password)
print(encrypted)
这会产生输出:MTE4NjkwMjEwMTIAAAAAALOizGhP2EU+svL69knoSys=
我在这里使用了aes256算法来加密消息。显然它们非常接近,但节点似乎用一些额外的字节填充输出。任何想法如何让两者互操作?
首先,在安全加密系统中,您应该期望每次加密时输出都不同,即使使用相同的代码也是如此。您的这一事实并不表明它是一种不安全的密码。通常,这是通过添加随机IV来完成的。
你的IV是“11869021012”,这很糟糕(因为它不是随机的,甚至不是16个字节),但它似乎你在两者中都以相同的方式使用它,所以这很好。
你的密码是一个字符串的SHA-256,这是一种创建密钥的可怕方式,但是,在这两种情况下你似乎都是这样做的,所以没关系。
您的问题是Python代码发出IV后跟密文。你的JS代码不会发出IV;它只发出密文。所以你可能在Python中意味着这个:
return base64.b64encode(cipher.encrypt(cleartext))
或者您需要重新编写JavaScript以在Base64编码之前将IV和密文粘合在一起。