python rsa加密
rsa 加密,是一个非对称加密,python中有多个 库可以使用,在此使用rsa库存
pip install rsa
假如使用4096 bit的密钥,
加密时每次可加密的字符长度是4096/8-11=501bytes,加上自身带的11bytes数据,
加密后的密文长度是512bytes
密钥长度越长,解密用时越长,要看CPU的性能
2048位的密钥大约是加密用时的22倍或更多,
4096位的密钥大约是加密用时的65倍或更多,
生成密钥对:
pubkey, privkey = rsa.newkeys(4096)
#把公钥写入到文件
pub = pubkey.save_pkcs1()
with open('pub.pem','wb') as wfs:
wfs.write(pub)
#把私钥写入到文件
priv = privkey.save_pkcs1()
with open('priv.pem','wb') as fs:
fs.write(priv)
加密文件:
加密和解密,都只能使用bytes类型,不能使用字符串等其它类型
#读取公钥
with open('pub.pem','rb') as rfs:
pubdata = rfs.read()
pubkey = rsa.PublicKey,load_pkcs1(pubdata)
#循环读取并加密文件
start = 0
with open('abc.txt','rb') as rfs:
with open('abc.encrypt.txt','wb') as wfs:
while start < os.path.getsize('abc.txt):
data = rfs.read(501)
#加密
encrypt_data = rsa.encrypt(data,pubkey) #data:要加密的数据;pubkey:公钥
wfs.write(encrypt_data)
start += 501
解密:
#读取私钥
with open('priv.pem','rb') as fs:
privdata = fs.read()
privkey = rsa.PrivateKey.load_pkcs1(privdata)
#循环读取并解密文件
start = 0
with open('abc.encrypt.txt','rb') as rfs:
with open('abc.decrypt.txt','wb') as wfs:
while start < os.path.getsize('abc.encrypt.txt):
data = rfs.read(512) #加密后的密文长度增加了11bytes
#加密
decrypt_data = rsa.encrypt(data,pubkey) #data:要解密的数据;pubkey:私钥
wfs.write(decrypt_data)
start += 501
字符串加解密:
先获取字符串长度,比较与密钥长度对应的固定长度,判断是否需要截取
a = 'abcdefg'
加密:
a = a.encode('utf-8')
length = len(a)
encrypt_data = b''
if length <= encrypt_length:
encrypt_data = rsa.encrypt(a,pubkey)
else:
start = 0
while start < length:
end = start + encrypt_length
data = a[start:end]
encrypt_data += rsa.encrypt(data,pubkey)
start =+ encrypt_length
return encrypt_data
解密同理:
length = len(a)
decrypt_data = ''
if length <= decrypt_length: # decrypt_length = encrypt_length +11
decrypt_data = rsa.decrypt(a,pubkey)
else:
start = 0
while start < length:
end = start + decrypt_length
data = a[start:end]
decrypt_data += rsa.decrypt(data,pubkey)
start =+ decrypt_length
return decrypt_data
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构