我有一堆数据,通过以下代码在 Ruby 中加密
text = '12345678'
key = '6b4f0a29d4bba86add88be9d'
cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').encrypt
cipher.key = key
s = cipher.update(text) + cipher.final
encrypted_text = s.unpack('H*')[0].upcase
# => 3B223AA60F1921F34CBBBAC209ACDCE4
可以在Ruby中解密
cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').decrypt
cipher.key = key
s = [encrypted_text].pack("H*").unpack("C*").pack("c*")
cipher.update(s) + cipher.final
# => 12345678
现在我必须用 Python 解密数据。 我写的加密代码如下:
from Crypto.Cipher import DES3
from Crypto import Random
from base64 import b64encode, b64decode
from Crypto.Util.Padding import pad, unpad
key = '6b4f0a29d4bba86add88be9d'
iv = Random.new().read(DES3.block_size)
cipher = DES3.new(key, DES3.MODE_CBC, iv)
text = '12345678'.encode()
encrypted = cipher.encrypt(text)
encrypted_text = encrypted.hex()
print(encrypted_text)
# => f84f555b02e3ee24
可以看到,加密后的数据差别很大,至少是长度不同。所以解密部分不起作用。 如何修改Python代码以兼容Ruby? 不幸的是,数据可以通过 ruby 应用程序获得,所以我只能修改 Python。
为了兼容 Ruby 代码,Python 代码缺少:
这样,Python 代码必须修复如下:
from Crypto.Cipher import DES3
from Crypto import Random
from base64 import b64encode, b64decode
from Crypto.Util.Padding import pad, unpad
key = '6b4f0a29d4bba86add88be9d'
iv = b'\0' * DES3.block_size # apply a zero IV
cipher = DES3.new(key, DES3.MODE_CBC, iv)
text = pad('12345678'.encode(), DES3.block_size) # pad
encrypted = cipher.encrypt(text)
encrypted_text = encrypted.hex()
print(encrypted_text.upper())
# => 3B223AA60F1921F34CBBBAC209ACDCE4
通过此更改,Python 代码提供了 Ruby 代码的结果。
但是请注意,该代码存在漏洞: