banner
stmoonar

stmoonar

无心而为
github
telegram
email
zhihu
x

一個簡單的文件加密python腳本

為了保存加密錢包私鑰,我寫了一個簡單的問價加密腳本,當然肯定也可以拿來加密一些其它東西。

之前一直把錢包助記詞粘貼在 txt 文件放在電腦上,但是想到萬一電腦硬盤突然壞了怎麼辦,上個月電腦主板直接壞了拿去修也沒修好,不過硬盤沒問題數據都在,只是有一些瀏覽器插件裡的錢包沒有備份助記詞的直接丟了,不過都是一些沒什麼東西的錢包。

那把文件上傳到雲端(之前我都是這麼備份的),但是最近看到網上傳的某雲盤的 bug,可以看到其他用戶存的文件,雖然也沒去探究是不是謠言,這也讓我不敢把明文直接存在雲端了。下面就是這個 python 腳本的代碼:

locker.py

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.ciphers.aead import AESGCM
import os
import sys
import getpass

def generate_key(password: str, salt: bytes) -> bytes:
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    return kdf.derive(password.encode())

def encrypt_file(password: str, input_file: str, output_file: str):
    salt = os.urandom(16)
    key = generate_key(password, salt)
    aesgcm = AESGCM(key)
    nonce = os.urandom(12)
  
    with open(input_file, 'rb') as f:
        data = f.read()
  
    encrypted_data = aesgcm.encrypt(nonce, data, None)
  
    with open(output_file, 'wb') as f:
        f.write(salt + nonce + encrypted_data)

def decrypt_file(password: str, input_file: str, output_file: str):
    with open(input_file, 'rb') as f:
        salt = f.read(16)
        nonce = f.read(12)
        encrypted_data = f.read()
  
    key = generate_key(password, salt)
    aesgcm = AESGCM(key)
  
    decrypted_data = aesgcm.decrypt(nonce, encrypted_data, None)
  
    with open(output_file, 'wb') as f:
        f.write(decrypted_data)

args = sys.argv

if len(args) != 4:
    print("Usage: python locker.py <op_type(encrypt/decrypt)> <input_file> <output_file>")
    sys.exit(1)

op_type = args[1]
input_file = args[2]
output_file = args[3]

password = getpass.getpass("Enter password: ")
if op_type == "encrypt":
    re_password = getpass.getpass("Re-enter password: ")
    if password != re_password:
        print("Passwords do not match")
        sys.exit(1)

if op_type == "encrypt":
    encrypt_file(password, input_file, output_file)
elif op_type == "decrypt":
    try:
        decrypt_file(password, input_file, output_file)
    except:
        print("Invalid password")
        sys.exit(1)
else:
    print("Invalid operation type")
    sys.exit(1)

使用 PBKDF2 算法加密,需要輸入自己的密碼才能解密,這樣至少提升了一個安全度,存在雲端洩露了也造成損失的概率也比較小。

使用方法:

python locker.py <op_type(encrypt/decrypt)> <input_file> <output_file>
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。