CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example08.py
Views: 729
1
"""
2
加密和解密
3
对称加密 - 加密和解密是同一个密钥 - DES / AES
4
非对称加密 - 加密和解密是不同的密钥 - RSA
5
pip install pycrypto
6
"""
7
import base64
8
9
from hashlib import md5
10
11
from Crypto.Cipher import AES
12
from Crypto import Random
13
from Crypto.PublicKey import RSA
14
15
# # AES加密的密钥(长度32个字节)
16
# key = md5(b'1qaz2wsx').hexdigest()
17
# # AES加密的初始向量(随机生成)
18
# iv = Random.new().read(AES.block_size)
19
20
21
def main():
22
"""主函数"""
23
# 生成密钥对
24
key_pair = RSA.generate(1024)
25
# 导入公钥
26
pub_key = RSA.importKey(key_pair.publickey().exportKey())
27
# 导入私钥
28
pri_key = RSA.importKey(key_pair.exportKey())
29
message1 = 'hello, world!'
30
# 加密数据
31
data = pub_key.encrypt(message1.encode(), None)
32
# 对加密数据进行BASE64编码
33
message2 = base64.b64encode(data[0])
34
print(message2)
35
# 对加密数据进行BASE64解码
36
data = base64.b64decode(message2)
37
# 解密数据
38
message3 = pri_key.decrypt(data)
39
print(message3.decode())
40
# # AES - 对称加密
41
# str1 = '我爱你们!'
42
# cipher = AES.new(key, AES.MODE_CFB, iv)
43
# # 加密
44
# str2 = cipher.encrypt(str1)
45
# print(str2)
46
# # 解密
47
# cipher = AES.new(key, AES.MODE_CFB, iv)
48
# str3 = cipher.decrypt(str2)
49
# print(str3.decode())
50
51
52
if __name__ == '__main__':
53
main()
54
55