新聞中心
在Python中,有多種方法可以加密文件,以下是一些常見的加密方法:

成都創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供正安網(wǎng)站建設(shè)、正安做網(wǎng)站、正安網(wǎng)站設(shè)計(jì)、正安網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、正安企業(yè)網(wǎng)站模板建站服務(wù),10余年正安做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
1、使用cryptography庫進(jìn)行AES加密
2、使用pycryptodome庫進(jìn)行AES加密
3、使用hashlib庫進(jìn)行哈希加密
4、使用base64庫進(jìn)行編碼加密
接下來,我們將詳細(xì)介紹這些方法。
1. 使用cryptography庫進(jìn)行AES加密
我們需要安裝cryptography庫,可以使用以下命令進(jìn)行安裝:
pip install cryptography
我們可以使用以下代碼對文件進(jìn)行AES加密:
from cryptography.fernet import Fernet
import os
生成密鑰
key = Fernet.generate_key()
cipher_suite = Fernet(key)
讀取文件內(nèi)容
with open("example.txt", "rb") as file:
file_data = file.read()
加密文件內(nèi)容
encrypted_data = cipher_suite.encrypt(file_data)
將加密后的內(nèi)容寫入新文件
with open("encrypted_example.txt", "wb") as file:
file.write(encrypted_data)
2. 使用pycryptodome庫進(jìn)行AES加密
我們需要安裝pycryptodome庫,可以使用以下命令進(jìn)行安裝:
pip install pycryptodome
我們可以使用以下代碼對文件進(jìn)行AES加密:
from Crypto.Cipher import AES
import os
生成密鑰
key = os.urandom(16)
cipher = AES.new(key, AES.MODE_EAX)
讀取文件內(nèi)容
with open("example.txt", "rb") as file:
file_data = file.read()
加密文件內(nèi)容
ciphertext, tag = cipher.encrypt_and_digest(file_data)
將加密后的內(nèi)容寫入新文件
with open("encrypted_example.txt", "wb") as file:
[file.write(x) for x in (cipher.nonce, tag, ciphertext)]
3. 使用hashlib庫進(jìn)行哈希加密
哈希加密是一種不可逆的加密方法,適用于驗(yàn)證數(shù)據(jù)的完整性,我們可以使用以下代碼對文件進(jìn)行哈希加密:
import hashlib
import os
計(jì)算文件的哈希值
def get_file_hash(file_path):
with open(file_path, "rb") as file:
file_data = file.read()
return hashlib.sha256(file_data).hexdigest()
獲取文件的哈希值并打印
print(get_file_hash("example.txt"))
4. 使用base64庫進(jìn)行編碼加密
Base64編碼是一種將二進(jìn)制數(shù)據(jù)轉(zhuǎn)換為文本的方法,通常用于在HTTP協(xié)議中傳輸二進(jìn)制數(shù)據(jù),我們可以使用以下代碼對文件進(jìn)行Base64編碼加密:
import base64
import os
讀取文件內(nèi)容并進(jìn)行Base64編碼加密
with open("example.txt", "rb") as file:
file_data = file.read()
encoded_data = base64.b64encode(file_data)
print(encoded_data)
以上就是Python中常見的幾種加密文件的方法,需要注意的是,這些加密方法都是對稱加密,即加密和解密使用相同的密鑰,在實(shí)際應(yīng)用中,需要確保密鑰的安全存儲和傳輸,對于非文本文件(如圖片、音頻等),我們可以直接對其二進(jìn)制內(nèi)容進(jìn)行加密,而無需先將其轉(zhuǎn)換為文本。
網(wǎng)站欄目:python如何加密文件
文章URL:http://fisionsoft.com.cn/article/djiecoo.html


咨詢
建站咨詢
