为什么在 php 中解密生成的字符串在 python 中解密时部分起作用?
Why decrypting string generated in php works partially while decrypting in python?
我正在开发小型应用程序,但在 python 中解密数据时遇到问题。
首先,我使用以下代码在 php 中使用 AES-256-CBC 加密字符串:
function EncryptAES($data){
global $KEY;
$ivlen = openssl_cipher_iv_length("aes-256-cbc");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($data, "aes-256-cbc", $KEY, NULL, $iv);
return $ciphertext;
}
现在 openssl_encrypt returns base64 字符串(因为我使用 NULL 作为第四个变量)
之后我试图在 python 中解密它,但它 returns 只是字符串的最后一部分。
这是 python 代码:
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-s[-1]]
class AESCipher:
def __init__( self, key ):
self.key = hashlib.sha256(key.encode('utf-8')).digest()
def decrypt( self, enc ):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[16:] ))
def Decrypt(data):
cipher = AESCipher(KEY)
decrypted = cipher.decrypt(data).decode('UTF-8')
return decrypted
当然KEY变量和服务器上的一样。
现在在 运行 Decrypt() 函数处理加密数据后 returns 只有部分解密字符串。
好的,问题解决了!
对于任何想知道的人,您需要在 php 中添加 IV。默认不添加 openssl_encrypt。
代码如下:
$ciphertext = openssl_encrypt($data, "aes-256-cbc", $KEY, OPENSSL_RAW_DATA, $iv);
$DATA = base64_encode($iv.$ciphertext);
我正在开发小型应用程序,但在 python 中解密数据时遇到问题。
首先,我使用以下代码在 php 中使用 AES-256-CBC 加密字符串:
function EncryptAES($data){
global $KEY;
$ivlen = openssl_cipher_iv_length("aes-256-cbc");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($data, "aes-256-cbc", $KEY, NULL, $iv);
return $ciphertext;
}
现在 openssl_encrypt returns base64 字符串(因为我使用 NULL 作为第四个变量)
之后我试图在 python 中解密它,但它 returns 只是字符串的最后一部分。
这是 python 代码:
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-s[-1]]
class AESCipher:
def __init__( self, key ):
self.key = hashlib.sha256(key.encode('utf-8')).digest()
def decrypt( self, enc ):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[16:] ))
def Decrypt(data):
cipher = AESCipher(KEY)
decrypted = cipher.decrypt(data).decode('UTF-8')
return decrypted
当然KEY变量和服务器上的一样。
现在在 运行 Decrypt() 函数处理加密数据后 returns 只有部分解密字符串。
好的,问题解决了! 对于任何想知道的人,您需要在 php 中添加 IV。默认不添加 openssl_encrypt。
代码如下:
$ciphertext = openssl_encrypt($data, "aes-256-cbc", $KEY, OPENSSL_RAW_DATA, $iv);
$DATA = base64_encode($iv.$ciphertext);