如何修改Python代码兼容Ruby的DES-EDE3-CBC加密解密逻辑?
兼容Ruby DES-EDE3-CBC加密数据的Python解密方案
问题背景
现有一批由Ruby代码通过DES-EDE3-CBC算法加密的数据,Ruby加密及解密逻辑如下:
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加密代码无法匹配Ruby的加密结果(长度、内容均不同),导致无法解密:
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
差异原因
- IV处理不同:Ruby的OpenSSL库在未显式指定IV时,默认使用全0的IV;Python代码中手动生成了随机IV,导致加密初始向量不一致
- 密钥解析不同:Ruby中
cipher.key = key会自动将十六进制字符串转换为字节;Python直接传入字符串会被当作ASCII字节处理,密钥解析错误 - 填充规则不同:Ruby的DES-EDE3-CBC默认使用PKCS#5填充,即使明文长度刚好等于块大小(8字节),仍会填充一个完整块;Python代码未显式调用填充逻辑,行为不匹配
兼容的Python解密代码
from Crypto.Cipher import DES3 from Crypto.Util.Padding import unpad # 将十六进制密钥转换为字节(和Ruby密钥解析逻辑对齐) key = bytes.fromhex('6b4f0a29d4bba86add88be9d') # 使用Ruby默认的全0IV iv = b'\x00' * DES3.block_size def decrypt_ruby_des3(encrypted_hex_str): # 将十六进制加密字符串转为字节数据 encrypted_data = bytes.fromhex(encrypted_hex_str) # 初始化CBC模式的3DES cipher cipher = DES3.new(key, DES3.MODE_CBC, iv) # 解密后移除PKCS#5填充 decrypted_bytes = unpad(cipher.decrypt(encrypted_data), DES3.block_size) return decrypted_bytes.decode('utf-8') # 测试Ruby生成的加密结果 test_encrypted = '3B223AA60F1921F34CBBBAC209ACDCE4' print(decrypt_ruby_des3(test_encrypted)) # => 12345678
代码要点说明
- 密钥必须通过
bytes.fromhex()转换为字节,确保和Ruby的密钥解析逻辑一致 - 强制使用全0的IV,匹配Ruby未指定IV时的默认行为
- 解密后必须调用
unpad()移除PKCS#5填充,因为Ruby即使明文长度刚好是块大小也会执行填充操作
内容的提问来源于stack exchange,提问作者Tiktac
相关产品推荐
相关产品推荐

