一个简单的文件加密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>
License:
CC BY 4.0