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