【发布时间】:2018-03-02 22:48:20
【问题描述】:
我有一个php文件,如下:
$encryption_encoded_key = 'c7e1wJFz+PBwQix80D1MbIwwOmOceZOzFGoidzDkF5g=';
function my_encrypt($data, $key) {
$encryption_key = base64_decode($key);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cfb'));
$encrypted = openssl_encrypt($data, 'aes-256-cfb', $encryption_key, 1, $iv);
// The $iv is just as important as the key for decrypting, so save it with encrypted data using a unique separator (::)
return base64_encode($encrypted . '::' . $iv);
}
function my_decrypt($data, $key) {
// Remove the base64 encoding from key
$encryption_key = base64_decode($key);
// To decrypt, split the encrypted data from IV - unique separator used was "::"
list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
return openssl_decrypt($encrypted_data, 'aes-256-cfb', $encryption_key, 1, $iv);
}
$data = 'USER_ID||NAME||EMAIL||MOBILE';
$data_encrypted = my_encrypt($data, $encryption_encoded_key);
echo $data_encrypted;
$data_decrypted = my_decrypt($data_encrypted, $encryption_encoded_key);
echo "Decrypted string: ". $data_decrypted;
这很好用,并且能够使用加密密钥进行加密/解密,现在我也有一个 python 文件:
import hashlib
import base64
from Crypto.Cipher import AES
from Crypto import Random
encryption_encoded_key = 'c7e1wJFz+PBwQix80D1MbIwwOmOceZOzFGoidzDkF5g='
def my_encrypt(data, key):
#Remove the base64 encoding from key
encryption_key = base64.b64decode(key)
#Generate an initialization vector
bs = AES.block_size
iv = Random.new().read(bs)
cipher = AES.new(encryption_key, AES.MODE_CFB, iv)
#Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
encrypted = cipher.encrypt(data)
#The iv is just as important as the key for decrypting, so save it with encrypted data using a unique separator (::)
return base64.b64encode(encrypted + '::' + iv)
def my_decrypt(data, key):
#Remove the base64 encoding from key
encryption_key = base64.b64decode(key)
#To decrypt, split the encrypted data from IV - unique separator used was "::"
encrypted_data, iv = base64.b64decode(data).split('::')
cipher = AES.new(encryption_key, AES.MODE_CFB, iv)
return cipher.decrypt(encrypted_data)
data = 'USER_ID||NAME||EMAIL||MOBILE'
print "Actual string: %s" %(data)
data_encrypted = my_encrypt(data, encryption_encoded_key)
print data_encrypted
data_decrypted = my_decrypt(data_encrypted, encryption_encoded_key)
print "Decrypted string: %s" %(data_decrypted)
当我尝试从 python 中使用它时,它也可以正常工作,它能够加密/解密输入字符串, 我想使用php文件加密并在python中解密输出,两者都应该使用CFB模式的AES 256加密,我做错了什么?
【问题讨论】:
-
流程哪里出了问题?在为每种方法运行加密/解密操作之前,您可以打印出您解析的密钥、iv、数据等吗?这至少会给你一个起点
-
哦,还有一件事要注意 - 对 python 或 php 了解不多,请注意参考类型。
iv在运行加密/解密操作时可能会通过每个块进行修改。如果您要(作为一个简单的例子)从...0001的iv 开始,在第一个块之后,该iv 可能表示为...0002。确保在两个实现中都附加了“原始”iv,而不是(可能)修改后的 iv。
标签: php python encryption cryptography aes