sách gpt4 ăn đã đi

python - AES Python 加密和 Ruby 加密 - 不同的行为?

In lại 作者:太空狗 更新时间:2023-10-29 20:54:15 26 4
mua khóa gpt4 giày nike

cái này 网站我有这个代码片段:

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> list(bytearray(ciphertext))
[214, 131, 141, 100, 33, 86, 84, 146, 170, 96, 65, 5, 224, 155, 139, 241]

当我将此数组转换为 Ruby 中的字符串并继续解密时,出现错误:

>> require 'openssl'
=> true
>> obj2 = OpenSSL::Cipher::Cipher.new("AES-128-CBC")
=> #
>> obj2.decrypt
=> #
>> obj2.key = 'This is a key123'
=> "This is a key123"
>> obj2.iv = 'This is an IV456'
=> "This is an IV456"
>> ciphertext = [214, 131, 141, 100, 33, 86, 84, 146, 170, 96, 65, 5, 224, 155, 139, 241].pack('c*')
=> "\xD6\x83\x8Dd!VT\x92\xAA`A\x05\xE0\x9B\x8B\xF1"
>> obj2.update(ciphertext) + obj2.final
OpenSSL::Cipher::CipherError: bad decrypt
from (irb):20:in `final'
from (irb):20
from /home/danyel/.rbenv/versions/2.0.0-p0/bin/irb:12:in `
'

为什么这不起作用?

câu trả lời hay nhất

这是可以理解的困惑——PyCrypto 在这里有点偏离轨道并且打破了通常的实现。如果您足够熟悉加密数据的正常外观,Python 输出看起来 显然是错误的,并为您提供了一个起点。如果不是,您很容易想知道到底出了什么问题,并且不知道从哪里开始寻找。

在“正常”实现中,默认情况下将使用填充,您最终(在这种情况下)会得到长 16 个字节的加密输出。

使用Ruby加密,例如,这是结果:

>> ciphertext
=> "\xD6\x83\x8Dd!VT\x92\xAA`A\x05\xE0\x9B\x8B\xF1\xD5f\xC7\xFFNI\xC7N\xBC-;!\f\xF1!\xB4"
>> ciphertext.bytes
=> [214, 131, 141, 100, 33, 86, 84, 146, 170, 96, 65, 5, 224, 155, 139, 241, 213, 102, 199, 255, 78, 73, 199, 78, 188, 45, 59, 33, 12, 241, 33, 180]

PyCrypto,出于我无法立即找到的原因,选择了 work only with unpadded data 。与 PyCrypto 交换数据时,您需要适本地配置任何其他库。

对于 Ruby 的 OpenSSL 库,Cipher 对象公开了一个 đệm lót 属性,可用于禁用填充:

>> require 'openssl'
=> true
>> obj2 = OpenSSL::Cipher::Cipher.new("AES-128-CBC")
=> #
>> obj2.decrypt
=> #
>> obj2.key = 'This is a key123'
=> "This is a key123"
>> obj2.iv = 'This is an IV456'
=> "This is an IV456"
>> obj2.padding = 0
=> 0
>> ciphertext = [214, 131, 141, 100, 33, 86, 84, 146, 170, 96, 65, 5, 224, 155, 139, 241].pack('c*')
=> "\xD6\x83\x8Dd!VT\x92\xAA`A\x05\xE0\x9B\x8B\xF1"
>> obj2.update(ciphertext) + obj2.final
=> "The answer is no"

关于python - AES Python 加密和 Ruby 加密 - 不同的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19661508/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress