fiyen commited on
Commit
4ae53f5
1 Parent(s): edab19c

Upload encrypt_it.py

Browse files
Files changed (1) hide show
  1. encrypt_it.py +46 -0
encrypt_it.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ from cryptography.fernet import Fernet
3
+ import base64
4
+
5
+ # 生成哈希密钥
6
+ def generate_key(username, password):
7
+ key = username.encode() + password.encode()
8
+ hash_key = hashlib.sha256(key).hexdigest().encode()[:32]
9
+ base64_key = base64.urlsafe_b64encode(hash_key)
10
+ return base64_key
11
+
12
+ # 加密函数,将明文加密成密文
13
+ def encrypt(message, key):
14
+ cipher = Fernet(key)
15
+ ciphertext = cipher.encrypt(message)
16
+ with open('encrypted.bin', 'wb') as f:
17
+ f.write(ciphertext)
18
+ return ciphertext
19
+
20
+ # 解密函数,将密文解密成明文
21
+ def decrypt(ciphertext, key):
22
+ cipher = Fernet(key)
23
+ plaintext = cipher.decrypt(ciphertext)
24
+ return plaintext
25
+
26
+
27
+ if __name__ == "__main__":
28
+ # 测试加解密函数
29
+ username = input('请输入用户名:')
30
+ password = input('请输入密码:')
31
+
32
+ # 生成哈希密钥
33
+ key = generate_key(username, password)
34
+
35
+ # # 加密数据并保存到文件中
36
+ # message = b'Hello, World!'
37
+ # ciphertext = encrypt(message, key)
38
+ # with open('encrypted.bin', 'wb') as f:
39
+ # f.write(ciphertext)
40
+
41
+ # 解密文件并输出明文数据
42
+ with open('encrypted.bin', 'rb') as f:
43
+ ciphertext = f.read()
44
+ key = generate_key(username, password)
45
+ plaintext = decrypt(ciphertext, key)
46
+ print(f'{username}的私密信息:{plaintext.decode()}')