Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby与Python中的AES加密差异_Python_Ruby_Encryption_Cryptography_Aes - Fatal编程技术网

Ruby与Python中的AES加密差异

Ruby与Python中的AES加密差异,python,ruby,encryption,cryptography,aes,Python,Ruby,Encryption,Cryptography,Aes,我试图使用AES-256-CBC加密消息,但在Ruby和Python版本中,我得到了不同的行为。Python的AES加密似乎没有添加后缀 require 'base64' require 'aescrypt' key = "z\r}\xE6\xB5\xB0P:\x80D@+\x96S\xAB (\x87\xDD#3x\xB9\xF3\xB4\xE7*qTKz\xC1" iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\

我试图使用AES-256-CBC加密消息,但在Ruby和Python版本中,我得到了不同的行为。Python的AES加密似乎没有添加后缀

require 'base64'
require 'aescrypt'

key = "z\r}\xE6\xB5\xB0P:\x80D@+\x96S\xAB (\x87\xDD#3x\xB9\xF3\xB4\xE7*qTKz\xC1"
iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
data = "\xC7u\xE7\xB7W\xED\xE60\xCD\n\xA1\x11;\xD1\x02f\x1A\xB3\x88)\xCAR\xA6B*\xB7\x82\x86/&\x86F"

Base64.encode64(AESCrypt.encrypt_data(data, key, iv, "AES-256-CBC"))

=> "ldB7M0nr+FP6I9NiogtvysUFfUC2vIt6Hj7cwzEiUEal76Cpyc+x6RTiHgkq\n6j7n\n"
而在使用
加密的Python中

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import base64
backend = default_backend()

key = "z\r}\xE6\xB5\xB0P:\x80D@+\x96S\xAB (\x87\xDD#3x\xB9\xF3\xB4\xE7*qTKz\xC1"
iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
data = "\xC7u\xE7\xB7W\xED\xE60\xCD\n\xA1\x11;\xD1\x02f\x1A\xB3\x88)\xCAR\xA6B*\xB7\x82\x86/&\x86F"

cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ct = encryptor.update(data) + encryptor.finalize()
base64.b64encode(ct)

=> 'ldB7M0nr+FP6I9NiogtvysUFfUC2vIt6Hj7cwzEiUEY='

您可以看到Ruby库生成的加密文本有额外的16个字节。我也有Java代码,它产生与Ruby版本完全相同的密文。Python代码的行为异常。如何更改Python代码,使其生成相同的密文?

一位朋友指出了问题:加密方法需要填充数据:

from Crypto.Util.Padding import pad
ct = encryptor.update(pad(data,16)) + encryptor.finalize()

看起来您正在使用Python 2。是这样吗?我记得几个月前我用加密软件包为AES CBC写了一个答案。你可能会发现它很有用。请注意PKCS7填充。你现在应该可以接受自己的答案了。