关键字:bytes str 加密 转换
最近在研究非对称加密,cryptography包得到的密文是bytes格式
想保存后再解密遇到问题
简单保存bytes到csv文件,密文会直接直接转成str
str文件通过encode()无法得到原来的密文
# ciphertext_message_bytes bytes格式密文
print(ciphertext_message_bytes)
ciphertext_message_str = str(ciphertext_message_bytes)
ciphertext_message_bytes = ciphertext_message_str.encode()
print(ciphertext_message_bytes)
原因:
密文是无意义字符串,不属于utf-8、gbk等编码字符集
encode直接对str编码,无法得到原来的bytes
解决方案:
加密保存过程:
bytes格式密文通过b64encode编码为base64格式,
base64格式密文转str保存
解密过程:
str转base64
base64转bytes格式
保存到文件中直接转成str格式
import base64
# 加密保存
print(ciphertext_message_bytes) # 初始密文
ciphertext_message_base64 = base64.b64encode(ciphertext_message_bytes) # bytes转base64
ciphertext_message = ciphertext_message_base64.decode() # base64转str
# 解密
ciphertext_base64 = ciphertext.encode() # str转base64
ciphertext_bytes = base64.b64decode(ciphertext_base64) # str转base64
print(ciphertext_bytes)
ciphertext_message_bytes和ciphertext_bytes 是一致的
本文探讨了非对称加密中密文的保存及读取问题,详细介绍了如何使用base64编码来确保密文在保存为字符串时不会发生改变,并成功实现了加密后的密文在保存与解密之间的正确转换。
4161

被折叠的 条评论
为什么被折叠?



