如何将Pycryptodome示例的文件读取逻辑适配为字符串变量?
替换Pycryptodome示例中的文件读取为字符串变量处理
原Pycryptodome示例通过文件对象的read()方法按固定长度读取加密数据,若你的加密数据存储在bytes类型变量中(加密数据为二进制,不能用普通字符串),可以通过维护偏移量+切片的方式模拟文件读取逻辑,实现相同的拆分效果:
方案1:分步拆分(可读性高)
from Crypto.PublicKey import RSA from Crypto.Cipher import AES, PKCS1_OAEP private_key = RSA.import_key(open("private.pem").read()) # 替换为你的实际二进制加密数据变量 encrypted_data = b"..." offset = 0 key_size = private_key.size_in_bytes() # 按原逻辑拆分数据 enc_session_key = encrypted_data[offset:offset+key_size] offset += key_size nonce = encrypted_data[offset:offset+16] offset += 16 tag = encrypted_data[offset:offset+16] offset += 16 # 读取剩余全部数据作为密文 ciphertext = encrypted_data[offset:]
方案2:模拟文件read方法(贴合原代码结构)
如果你希望保留原列表推导式的写法,可以封装一个模拟文件read()的函数:
from Crypto.PublicKey import RSA from Crypto.Cipher import AES, PKCS1_OAEP private_key = RSA.import_key(open("private.pem").read()) encrypted_data = b"..." # 你的二进制加密数据变量 offset = 0 def read_bytes(x): nonlocal offset if x == -1: # 读取剩余全部数据 result = encrypted_data[offset:] offset = len(encrypted_data) else: # 读取指定长度数据 result = encrypted_data[offset:offset+x] offset += x return result # 完全复用原代码的列表推导式结构 enc_session_key, nonce, tag, ciphertext = [read_bytes(x) for x in (private_key.size_in_bytes(), 16, 16, -1)]
注意事项
- 确保你的加密数据变量是bytes类型:如果数据原本是字符串,需要先通过
your_str.encode()或指定编码转成bytes,但加密后的原始数据通常直接为bytes类型,无需额外转换。 - 偏移量的维护要严格对应原文件读取的顺序,避免拆分位置错误导致解密失败。
内容的提问来源于stack exchange,提问作者rex_nebula
相关产品推荐
相关产品推荐

