python rsa模塊【sign 加簽驗簽】的使用


https://www.cnblogs.com/kayb/p/8157556.html

https://www.jianshu.com/p/518fa5d59f89

**https://blog.csdn.net/ctwy291314/article/details/88822130

公鑰加密、私鑰解密

 1 # -*- coding: utf-8 -*-
 2 import rsa
 3 
 4 # rsa加密
 5 def rsaEncrypt(str):
 6     # 生成公鑰、私鑰
 7     (pubkey, privkey) = rsa.newkeys(512)
 8     print("pub: ", pubkey)
 9     print("priv: ", privkey)
10     # 明文編碼格式
11     content = str.encode('utf-8')
12     # 公鑰加密
13     crypto = rsa.encrypt(content, pubkey)
14     return (crypto, privkey)
15 
16 
17 # rsa解密
18 def rsaDecrypt(str, pk):
19     # 私鑰解密
20     content = rsa.decrypt(str, pk)
21     con = content.decode('utf-8')
22     return con
23 
24 
25 (a, b) = rsaEncrypt("hello")
26 print('加密后密文:')
27 print(a)
28 content = rsaDecrypt(a, b)
29 print('解密后明文:')
30 print(content)  

密鑰導出、簽名驗證

 1 # -*- coding: utf-8 -*-
 2 import rsa
 3 
 4 # 先生成一對密鑰,然后保存.pem格式文件,當然也可以直接使用
 5 (pubkey, privkey) = rsa.newkeys(1024)
 6 
 7 pub = pubkey.save_pkcs1()
 8 pubfile = open('public.pem', 'wb')
 9 pubfile.write(pub)
10 pubfile.close()
11 
12 pri = privkey.save_pkcs1()
13 prifile = open('private.pem', 'wb')
14 prifile.write(pri)
15 prifile.close()
16 
17 # load公鑰和密鑰
18 message = 'lovesoo.org'
19 with open('public.pem', "rb") as publickfile:
20     p = publickfile.read()
21     pubkey = rsa.PublicKey.load_pkcs1(p)
22     print(pubkey)
23 with open('private.pem', "rb") as privatefile:
24     p = privatefile.read()
25     privkey = rsa.PrivateKey.load_pkcs1(p)
26     print(privkey)
27 # 用公鑰加密、再用私鑰解密
28 crypto = rsa.encrypt(message.encode('utf-8'), pubkey)
29 message = rsa.decrypt(crypto, privkey)
30 message = message.decode('utf-8')
31 print (message)
32 
33 # sign 用私鑰簽名認證、再用公鑰驗證簽名
34 signature = rsa.sign(message.encode('utf-8'), privkey, 'SHA-1')
35 method_name = rsa.verify('lovesoo.org'.encode('utf-8'), signature, pubkey)
36 print(method_name)

對文件進行RSA加密解密

from rsa.bigfile import *
import rsa

with open('public.pem') as publickfile:
    p = publickfile.read()
    pubkey = rsa.PublicKey.load_pkcs1(p)

with open('private.pem') as privatefile:
    p = privatefile.read()
    privkey = rsa.PrivateKey.load_pkcs1(p)
with open('mysec.txt', 'rb') as infile, open('outputfile', 'wb') as outfile: #加密輸出
    encrypt_bigfile(infile, outfile, pubkey)

with open('outputfile', 'rb') as infile2, open('result', 'wb') as outfile2:  #解密輸出
    decrypt_bigfile(infile2, outfile2, privkey)

4.0的主要變化
版本3.4是3.x范圍內的最后一個版本。版本4.0刪除了以下模塊,因為它們不安全:

rsa._version133
rsa._version200
rsa.bigfile
rsa.varblock
這些模塊在3.4版中被標記為已棄用。

此外,在4.0中,I / O函數經過簡化,可以在所有支持的Python版本上使用字節。

4.0版本不再支持Python 2.6和3.3。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM