Python加密操作 对称加密/非对称加密

安装包: 

pycryptodome

https://pycryptodome.readthedocs.io/en/latest/src/installation.html#compiling-in-linux-ubuntu

 

 1 from Crypto.Hash import SHA256
 2 from Crypto.PublicKey import RSA
 3 from Crypto import Random
 4 from Crypto.Signature import pkcs1_15
 5 from Crypto.Cipher import PKCS1_v1_5
 6 
 7 key = RSA.generate(1024)
 8 # 公钥 私钥
 9 pri_key_text = key.export_key()
10 pub_key_text = key.public_key().export_key()
11 
12 pub_key = RSA.import_key(pub_key_text)
13 pri_key = RSA.import_key(pri_key_text)
14 
15 # 加密
16 text = b'abcdefg'
17 cipher = PKCS1_v1_5.new(pub_key)
18 etext = cipher.encrypt(text)
19 
20 # 解密
21 cipher_de = PKCS1_v1_5.new(pri_key)
22 dtext = cipher_de.decrypt(etext,None)
23 
24 # 签名
25 dg = SHA256.new(text)
26 sign = pkcs1_15.new(pri_key).sign(dg)
27 
28 # 签名验证
29 dg2 = SHA256.new(dtext)
30 try:
31     pkcs1_15.new(pub_key).verify(dg2, sign)
32 except ValueError:
33     print('验证失败')
34 
35 # 对称加密
36 
37 from Crypto.Random import get_random_bytes
38 from Crypto.Cipher import AES
39 from Crypto.Util.Padding import pad, unpad
40 
41 key = get_random_bytes(16)
42 cipher = AES.new(key, AES.MODE_CBC)
43 edata = cipher.encrypt(pad(text, AES.block_size))
44 
45 cipher_d = AES.new(key, AES.MODE_CBC, cipher.iv)
46 unpad(cipher_d.decrypt(edata),AES.block_size)

 

posted @ 2022-12-02 02:22  酱_油  阅读(359)  评论(0编辑  收藏  举报