Python知識(shí)分享網(wǎng) - 專業(yè)的Python學(xué)習(xí)網(wǎng)站 學(xué)Python,上Python222
Python文件加密:構(gòu)建一個(gè)簡(jiǎn)單的加密工具 PDF 下載
發(fā)布于:2024-07-29 11:19:09
(假如點(diǎn)擊沒(méi)反應(yīng),多刷新兩次就OK!)

Python文件加密:構(gòu)建一個(gè)簡(jiǎn)單的加密工具  PDF 下載 圖1

 

資料內(nèi)容:

 

在數(shù)字時(shí)代,數(shù)據(jù)安全變得愈發(fā)重要。文件加密是一種常見的保護(hù)數(shù)據(jù)安全的方法。通過(guò)加
密文件,可以防止未經(jīng)授權(quán)的訪問(wèn)和數(shù)據(jù)泄露。Python 作為一種廣泛使用的編程語(yǔ)言,提
供了多種工具和庫(kù)來(lái)實(shí)現(xiàn)文件加密。本文將詳細(xì)介紹如何在 Python 中實(shí)現(xiàn)一個(gè)簡(jiǎn)單的文件
加密工具。
### 文件加密的基本概念
文件加密是將文件內(nèi)容轉(zhuǎn)換成不可讀的格式,只有擁有解密密鑰的人才能將其還原為原始數(shù)
據(jù)。常見的加密算法包括對(duì)稱加密(如 AES)和非對(duì)稱加密(如 RSA)。在本文中,我們將
使用對(duì)稱加密算法來(lái)實(shí)現(xiàn)文件加密和解密。
### Python 中的加密庫(kù)
Python `cryptography`庫(kù)是一個(gè)強(qiáng)大的加密工具包,支持多種加密算法和協(xié)議。首先,你
需要安裝這個(gè)庫(kù):
```bash
pip install cryptography
```
### 使用 AES 算法加密文件
AES(高級(jí)加密標(biāo)準(zhǔn))是一種廣泛使用的對(duì)稱加密算法。以下是使用 AES 算法加密文件的基
本步驟:
1. **生成密鑰**:首先需要生成一個(gè)密鑰,這個(gè)密鑰將用于加密和解密文件。
2. **初始化向量(IV**:為了提高安全性,每次加密時(shí)都應(yīng)使用一個(gè)隨機(jī)的初始化向量。
3. **加密文件**:使用密鑰和 IV 對(duì)文件內(nèi)容進(jìn)行加密。
4. **存儲(chǔ)加密文件和 IV**:將加密后的文件和 IV 存儲(chǔ)在磁盤上。
以下是具體的代碼實(shí)現(xiàn):
```python
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
import os
def generate_key(password: str, salt: bytes):
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
return kdf.derive(password.encode())
def encrypt_file(input_file_path: str, output_file_path: str, password: str):
salt = os.urandom(16)
key = generate_key(password, salt)
iv = os.urandom(16)
# 創(chuàng)建加密器
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
encryptor = cipher.encryptor()
# 讀取原始文件內(nèi)容
with open(input_file_path, 'rb') as file:
plaintext = file.read()
padded_plaintext = padding.pad(plaintext, algorithms.AES.block_size)
# 加密文件內(nèi)容
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
# 將加密后的內(nèi)容、IV 和鹽寫入輸出文件
with open(output_file_path, 'wb') as file:
file.write(salt + iv + ciphertext)
return salt, iv
def main():
password = input("Enter a password: ")
input_file_path = input("Enter the path to the file to encrypt: ")
output_file_path = input("Enter the path for the encrypted file: ")
salt, iv = encrypt_file(input_file_path, output_file_path, password)
print(f"File encrypted successfully. Salt: {salt.hex()}, IV: {iv.hex()}")
if __name__ == "__main__":
main()
```