有时候我们手中文件的内容十分的重要、十分地机密,我们可以选择对此进行加密,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
from cryptography.fernet import Fernet
def encrypt(filename, key):
fernet = Fernet(key)
with open(filename, 'rb') as file:
original = file.read()
encrypted = fernet.encrypt(original)
with open(filename, 'wb') as enc_file:
enc_file.write(encrypted)
key = Fernet.generate_key()
filename = "file.txt"
encrypt(filename, key)
|
我们生成密钥,然后对文件内容进行加密,当然这个密钥后面在对文件进行解密的时候会派上用场,因此密钥一定要保存完好,解密的代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
def decrypt(filename, key):
fernet = Fernet(key)
with open(filename, 'rb') as enc_file:
encrypted = enc_file.read()
decrypted = fernet.decrypt(encrypted)
with open(filename, 'wb') as dec_file:
dec_file.write(decrypted)
decrypt(filename, key)
|
上面的脚本,其中的密钥是一个随机生成的随机数,当然密钥也可以是我们自己指定的,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import pyAesCrypt
def Encryption(input_file_path, output_file_path, key):
pyAesCrypt.encryptFile(input_file_path, output_file_path, key)
print("File has been decrypted")
def Decryption(input_file_path, output_file_path, key):
pyAesCrypt.decryptFile(input_file_path, output_file_path, key)
print("File has been decrypted")
|