首頁 > 後端開發 > Python教學 > python怎麼開啟加密的文件

python怎麼開啟加密的文件

下次还敢
發布: 2024-04-11 01:26:23
原創
665 人瀏覽過

在Python 中開啟加密檔案需要:1. 安裝cryptography 庫;2. 導入庫;3. 取得加密金鑰;4. 建立Fernet 物件;5. 開啟並讀取加密檔案;6. 解密資料;7.寫入解密檔案。

python怎麼開啟加密的文件

如何利用Python 開啟加密檔案

在Python 中,開啟加密檔案涉及以下步驟:

1. 安裝必要的函式庫

要解密文件,您需要安裝cryptography 函式庫。使用下列指令安裝:

<code>pip install cryptography</code>
登入後複製

2. 匯入庫

在您的Python 腳本中,匯入cryptography 函式庫:

import cryptography
from cryptography.fernet import Fernet
登入後複製

3. 取得加密金鑰

解密檔案需要加密金鑰。這個金鑰應該是一個位元組字串:

encryption_key = b'' # 这里填写您的加密密钥字节字符串
登入後複製

4. 建立Fernet 物件

Fernet 物件用於解密檔案:

fernet = Fernet(encryption_key)
登入後複製

#5. 開啟並讀取加密檔案

with open('encrypted_file.txt', 'rb') as f:
    encrypted_data = f.read()
登入後複製

6. 解密資料

decrypted_data = fernet.decrypt(encrypted_data)
登入後複製

7.寫入解密檔案

############################# ##
with open('decrypted_file.txt', 'wb') as f:
    f.write(decrypted_data)
登入後複製
######範例:######
import cryptography
from cryptography.fernet import Fernet

encryption_key = b'YOUR_ENCRYPTION_KEY_BYTE_STRING'
fernet = Fernet(encryption_key)

with open('encrypted_file.txt', 'rb') as f:
    encrypted_data = f.read()

decrypted_data = fernet.decrypt(encrypted_data)

with open('decrypted_file.txt', 'wb') as f:
    f.write(decrypted_data)
登入後複製

以上是python怎麼開啟加密的文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
python - ubuntu16.04 lxml的報錯
來自於 1970-01-01 08:00:00
0
0
0
有辦法在PHP裡寫Python嗎?
來自於 1970-01-01 08:00:00
0
0
0
python scrapy爬蟲錯誤
來自於 1970-01-01 08:00:00
0
0
0
python相關問題求解決,有償
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板