非对称加密后bytes密文转str保存再解密

关键字: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 是一致的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

779醒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值