python3加密 解密 签名 验签

 1 from Crypto import Random
 2 from Crypto.Hash import SHA
 3 from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
 4 from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
 5 from Crypto.PublicKey import RSA
 6 import base64
 7 
 8 # 加密解密:公钥加密,私钥解密
 9 #
10 # 签名验签:私钥签名,公钥验签
11 #
12 # 生成 private key and pulic key
13 print("1、生成 private key and pulic key")
14 
15 # 伪随机数生成器
16 random_generator = Random.new().read
17 # rsa算法生成实例
18 rsa = RSA.generate(1024, random_generator)
19 
20 # master的秘钥对的生成
21 private_pem = rsa.exportKey()
22 
23 with open('master-private.pem', 'wb') as f:
24     f.write(private_pem)
25 
26 public_pem = rsa.publickey().exportKey()
27 with open('master-public.pem', 'wb') as f:
28     f.write(public_pem)
29 
30 # ghost的秘钥对的生成
31 private_pem = rsa.exportKey()
32 with open('ghost-private.pem', 'wb') as f:
33     f.write(private_pem)
34 
35 public_pem = rsa.publickey().exportKey()
36 with open('ghost-public.pem', 'wb') as f:
37     f.write(public_pem)
38 
39 # 加密和解密
40 print("2、加密和解密")
41 # Master使用Ghost的公钥对内容进行rsa 加密
42 
43 message = 'hello ghost, this is a plian text'
44 print("message: " + message)
45 with open('ghost-public.pem') as f:
46     key = f.read()
47     rsakey = RSA.importKey(key)
48     cipher = Cipher_pkcs1_v1_5.new(rsakey)
49     cipher_text = base64.b64encode(cipher.encrypt(message.encode()))
50     print("加密(encrypt)")
51     print(cipher_text)
52 
53 # Ghost使用自己的私钥对内容进行rsa 解密
54 
55 with open('ghost-private.pem') as f:
56     key = f.read()
57     rsakey = RSA.importKey(key)
58     cipher = Cipher_pkcs1_v1_5.new(rsakey)
59     text = cipher.decrypt(base64.b64decode(cipher_text), random_generator)
60 
61     print("解密(decrypt)")
62     print("message:" + text.decode())
63 
64     assert text.decode() == message, 'decrypt falied'
65 
66 # 签名与验签
67 print("3、 签名与验签")
68 
69 # Master 使用自己的私钥对内容进行签名
70 print("签名")
71 with open('master-private.pem') as f:
72     key = f.read()
73     rsakey = RSA.importKey(key)
74     signer = Signature_pkcs1_v1_5.new(rsakey)
75     digest = SHA.new()
76     digest.update(message.encode())
77     sign = signer.sign(digest)
78     signature = base64.b64encode(sign)
79 
80 print(signature)
81 
82 print("验签")
83 with open('master-public.pem') as f:
84     key = f.read()
85     rsakey = RSA.importKey(key)
86     verifier = Signature_pkcs1_v1_5.new(rsakey)
87     digest = SHA.new()
88     # Assumes the data is base64 encoded to begin with
89     digest.update(message.encode())
90     is_verify = verifier.verify(digest, base64.b64decode(signature))
91 
92 print(is_verify)

 

posted on 2018-07-19 10:03  sammy1989  阅读(2060)  评论(0编辑  收藏  举报

导航