本文目录导读:

Python 实现(推荐)
使用 cryptography 库(AES加密)
# 安装:pip install cryptography
from cryptography.fernet import Fernet
import os
class FileEncryptor:
def __init__(self):
self.key = None
def generate_key(self):
"""生成加密密钥"""
self.key = Fernet.generate_key()
return self.key
def save_key(self, key_file):
"""保存密钥到文件"""
with open(key_file, 'wb') as f:
f.write(self.key)
def load_key(self, key_file):
"""从文件加载密钥"""
with open(key_file, 'rb') as f:
self.key = f.read()
def encrypt_file(self, input_file, output_file=None):
"""加密文件"""
if not output_file:
output_file = input_file + '.encrypted'
if not self.key:
self.generate_key()
fernet = Fernet(self.key)
with open(input_file, 'rb') as f:
file_data = f.read()
encrypted_data = fernet.encrypt(file_data)
with open(output_file, 'wb') as f:
f.write(encrypted_data)
return output_file
def decrypt_file(self, input_file, output_file=None):
"""解密文件"""
if not output_file:
output_file = input_file.replace('.encrypted', '.decrypted')
if not self.key:
raise ValueError("密钥未设置")
fernet = Fernet(self.key)
with open(input_file, 'rb') as f:
encrypted_data = f.read()
decrypted_data = fernet.decrypt(encrypted_data)
with open(output_file, 'wb') as f:
f.write(decrypted_data)
return output_file
# 使用示例
if __name__ == "__main__":
encryptor = FileEncryptor()
# 加密文件
key = encryptor.generate_key()
encryptor.save_key('secret.key')
encryptor.encrypt_file('important.txt', 'important.encrypted')
# 解密文件
encryptor.load_key('secret.key')
encryptor.decrypt_file('important.encrypted', 'important_restored.txt')
使用密码加密(用户友好)
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2
import base64
import os
class PasswordFileEncryptor:
def __init__(self):
self.salt = None
def _generate_key_from_password(self, password: str) -> bytes:
"""从密码生成密钥"""
if not self.salt:
self.salt = os.urandom(16)
kdf = PBKDF2(
algorithm=hashes.SHA256(),
length=32,
salt=self.salt,
iterations=100000,
)
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
return key
def encrypt_file(self, input_file: str, password: str, output_file: str = None):
"""使用密码加密文件"""
if not output_file:
output_file = input_file + '.encrypted'
# 生成密钥
self.salt = os.urandom(16)
key = self._generate_key_from_password(password)
fernet = Fernet(key)
with open(input_file, 'rb') as f:
file_data = f.read()
encrypted_data = fernet.encrypt(file_data)
# 保存salt和加密数据
with open(output_file, 'wb') as f:
f.write(self.salt)
f.write(encrypted_data)
return output_file
def decrypt_file(self, input_file: str, password: str, output_file: str = None):
"""使用密码解密文件"""
if not output_file:
output_file = input_file.replace('.encrypted', '_restored')
with open(input_file, 'rb') as f:
self.salt = f.read(16) # 读取salt
encrypted_data = f.read()
key = self._generate_key_from_password(password)
fernet = Fernet(key)
decrypted_data = fernet.decrypt(encrypted_data)
with open(output_file, 'wb') as f:
f.write(decrypted_data)
return output_file
# 使用示例
encryptor = PasswordFileEncryptor()
encryptor.encrypt_file('secret.txt', 'my_password123', 'secret.encrypted')
encryptor.decrypt_file('secret.encrypted', 'my_password123', 'secret.txt')
Bash/Shell 脚本(使用 OpenSSL)
#!/bin/bash
# 文件加密函数
encrypt_file() {
local input_file=$1
local output_file=$2
local password=$3
if [ -z "$password" ]; then
read -s -p "Enter encryption password: " password
echo
fi
# 使用 OpenSSL AES-256-CBC 加密
openssl enc -aes-256-cbc -salt -pbkdf2 -in "$input_file" -out "${output_file:-$input_file.enc}" -pass pass:"$password"
if [ $? -eq 0 ]; then
echo "File encrypted successfully: ${output_file:-$input_file.enc}"
else
echo "Encryption failed!"
return 1
fi
}
# 文件解密函数
decrypt_file() {
local input_file=$1
local output_file=$2
local password=$3
if [ -z "$password" ]; then
read -s -p "Enter decryption password: " password
echo
fi
# 使用 OpenSSL AES-256-CBC 解密
openssl enc -d -aes-256-cbc -pbkdf2 -in "$input_file" -out "${output_file:-${input_file%.enc}}" -pass pass:"$password"
if [ $? -eq 0 ]; then
echo "File decrypted successfully: ${output_file:-${input_file%.enc}}"
else
echo "Decryption failed! Wrong password or corrupted file."
return 1
fi
}
# 使用 OpenSSL 生成密钥
generate_key() {
openssl rand -base64 32 > secret.key
echo "Key generated and saved to secret.key"
}
# 使用密钥文件的加密
encrypt_with_key() {
local input_file=$1
local key_file=${2:-secret.key}
local output_file=${3:-$input_file.enc}
openssl enc -aes-256-cbc -salt -pbkdf2 -in "$input_file" -out "$output_file" -pass file:"$key_file"
}
decrypt_with_key() {
local input_file=$1
local key_file=${2:-secret.key}
local output_file=${3:-${input_file%.enc}}
openssl enc -d -aes-256-cbc -pbkdf2 -in "$input_file" -out "$output_file" -pass file:"$key_file"
}
# 主菜单
main() {
echo "File Encryption/Decryption Tool"
echo "1. Encrypt file"
echo "2. Decrypt file"
echo "3. Encrypt with key file"
echo "4. Decrypt with key file"
echo "5. Generate key"
echo "6. Exit"
read -p "Choose option: " choice
case $choice in
1)
read -p "Input file: " input
read -p "Output file (optional): " output
encrypt_file "$input" "$output"
;;
2)
read -p "Input file: " input
read -p "Output file (optional): " output
decrypt_file "$input" "$output"
;;
3)
read -p "Input file: " input
read -p "Key file (default: secret.key): " key
read -p "Output file (optional): " output
encrypt_with_key "$input" "$key" "$output"
;;
4)
read -p "Input file: " input
read -p "Key file (default: secret.key): " key
read -p "Output file (optional): " output
decrypt_with_key "$input" "$key" "$output"
;;
5)
generate_key
;;
6)
exit 0
;;
*)
echo "Invalid option"
;;
esac
}
# 运行主菜单
main
PowerShell 脚本
# FileEncryptor.ps1
function Encrypt-File {
param(
[Parameter(Mandatory=$true)]
[string]$InputFile,
[Parameter(Mandatory=$false)]
[string]$OutputFile,
[Parameter(Mandatory=$false)]
[securestring]$Password
)
if (-not $OutputFile) {
$OutputFile = "$InputFile.enc"
}
if (-not $Password) {
$Password = Read-Host "Enter password" -AsSecureString
$ConfirmPassword = Read-Host "Confirm password" -AsSecureString
# 验证密码
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$BSTR2 = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($ConfirmPassword)
$PlainPassword2 = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR2)
if ($PlainPassword -ne $PlainPassword2) {
Write-Error "Passwords do not match!"
return
}
}
# 使用 AES 加密
$Content = Get-Content $InputFile -Raw
$SecureString = ConvertTo-SecureString $Content -AsPlainText -Force
$Encrypted = ConvertFrom-SecureString $SecureString -SecureKey $Password
$Encrypted | Out-File $OutputFile
Write-Host "File encrypted successfully: $OutputFile"
}
function Decrypt-File {
param(
[Parameter(Mandatory=$true)]
[string]$InputFile,
[Parameter(Mandatory=$false)]
[string]$OutputFile,
[Parameter(Mandatory=$false)]
[securestring]$Password
)
if (-not $OutputFile) {
$OutputFile = [System.IO.Path]::ChangeExtension($InputFile, ".dec")
}
if (-not $Password) {
$Password = Read-Host "Enter password" -AsSecureString
}
$Encrypted = Get-Content $InputFile -Raw
$SecureString = ConvertTo-SecureString $Encrypted -SecureKey $Password
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
$Decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$Decrypted | Out-File $OutputFile -Encoding UTF8
Write-Host "File decrypted successfully: $OutputFile"
}
# 导出函数
Export-ModuleMember -Function Encrypt-File, Decrypt-File
Python GUI 版本(使用 Tkinter)
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from cryptography.fernet import Fernet
import os
class FileEncryptorGUI:
def __init__(self, root):
self.root = root
self.root.title("文件加密解密工具")
self.root.geometry("600x400")
self.key = None
self.selected_file = None
self.setup_ui()
def setup_ui(self):
# 文件选择
frame_file = ttk.LabelFrame(self.root, text="文件选择", padding=10)
frame_file.pack(fill="x", padx=10, pady=5)
self.file_path = tk.StringVar()
ttk.Entry(frame_file, textvariable=self.file_path, width=50).pack(side="left", padx=5)
ttk.Button(frame_file, text="浏览", command=self.select_file).pack(side="left")
# 密钥管理
frame_key = ttk.LabelFrame(self.root, text="密钥管理", padding=10)
frame_key.pack(fill="x", padx=10, pady=5)
ttk.Button(frame_key, text="生成密钥", command=self.generate_key).pack(side="left", padx=5)
ttk.Button(frame_key, text="加载密钥", command=self.load_key).pack(side="left", padx=5)
ttk.Button(frame_key, text="保存密钥", command=self.save_key).pack(side="left", padx=5)
# 密码加密
frame_password = ttk.LabelFrame(self.root, text="密码加密", padding=10)
frame_password.pack(fill="x", padx=10, pady=5)
ttk.Label(frame_password, text="密码:").pack(side="left")
self.password = tk.StringVar()
ttk.Entry(frame_password, textvariable=self.password, show="*", width=20).pack(side="left", padx=5)
# 操作按钮
frame_action = ttk.Frame(self.root, padding=10)
frame_action.pack(fill="x", padx=10, pady=5)
ttk.Button(frame_action, text="加密文件", command=self.encrypt_file, width=15).pack(side="left", padx=5)
ttk.Button(frame_action, text="解密文件", command=self.decrypt_file, width=15).pack(side="left", padx=5)
# 状态显示
self.status_text = tk.Text(self.root, height=10, wrap=tk.WORD)
self.status_text.pack(fill="both", expand=True, padx=10, pady=5)
scrollbar = ttk.Scrollbar(self.status_text)
scrollbar.pack(side="right", fill="y")
self.status_text.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.status_text.yview)
def log(self, message):
self.status_text.insert(tk.END, f"{message}\n")
self.status_text.see(tk.END)
def select_file(self):
file_path = filedialog.askopenfilename()
if file_path:
self.file_path.set(file_path)
self.selected_file = file_path
self.log(f"选择的文件: {file_path}")
def generate_key(self):
self.key = Fernet.generate_key()
self.log("新密钥已生成")
def load_key(self):
key_file = filedialog.askopenfilename(title="选择密钥文件")
if key_file:
with open(key_file, 'rb') as f:
self.key = f.read()
self.log(f"密钥已加载: {key_file}")
def save_key(self):
if not self.key:
messagebox.showerror("错误", "请先生成或加载密钥")
return
key_file = filedialog.asksaveasfilename(title="保存密钥文件", defaultextension=".key")
if key_file:
with open(key_file, 'wb') as f:
f.write(self.key)
self.log(f"密钥已保存: {key_file}")
def encrypt_file(self):
if not self.selected_file:
messagebox.showerror("错误", "请先选择文件")
return
# 使用密码加密
if self.password.get():
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2
import base64
salt = os.urandom(16)
kdf = PBKDF2(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000
)
key = base64.urlsafe_b64encode(kdf.derive(self.password.get().encode()))
fernet = Fernet(key)
elif self.key:
fernet = Fernet(self.key)
else:
messagebox.showerror("错误", "请设置密码或加载密钥")
return
try:
with open(self.selected_file, 'rb') as f:
data = f.read()
encrypted_data = fernet.encrypt(data)
output_file = self.selected_file + ".encrypted"
with open(output_file, 'wb') as f:
f.write(encrypted_data)
self.log(f"文件加密成功: {output_file}")
messagebox.showinfo("成功", "文件加密完成!")
except Exception as e:
self.log(f"加密失败: {str(e)}")
messagebox.showerror("错误", f"加密失败: {str(e)}")
def decrypt_file(self):
if not self.selected_file:
messagebox.showerror("错误", "请先选择文件")
return
# 使用密码解密
if self.password.get():
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2
import base64
salt = os.urandom(16)
kdf = PBKDF2(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000
)
key = base64.urlsafe_b64encode(kdf.derive(self.password.get().encode()))
fernet = Fernet(key)
elif self.key:
fernet = Fernet(self.key)
else:
messagebox.showerror("错误", "请设置密码或加载密钥")
return
try:
with open(self.selected_file, 'rb') as f:
data = f.read()
decrypted_data = fernet.decrypt(data)
# 生成输出文件名
base_name = os.path.splitext(self.selected_file)[0]
if self.selected_file.endswith('.encrypted'):
output_file = base_name
else:
output_file = base_name + ".decrypted"
with open(output_file, 'wb') as f:
f.write(decrypted_data)
self.log(f"文件解密成功: {output_file}")
messagebox.showinfo("成功", "文件解密完成!")
except Exception as e:
self.log(f"解密失败: {str(e)}")
messagebox.showerror("错误", f"解密失败: {str(e)}")
if __name__ == "__main__":
root = tk.Tk()
app = FileEncryptorGUI(root)
root.mainloop()
使用方法
Python 版本
# 安装依赖 pip install cryptography # 运行脚本 python file_encryptor.py
Shell 版本
# 添加执行权限 chmod +x file_encryptor.sh # 运行 ./file_encryptor.sh
PowerShell 版本
# 加载模块 Import-Module ./FileEncryptor.ps1 # 使用函数 Encrypt-File -InputFile "secret.txt" -OutputFile "secret.enc" Decrypt-File -InputFile "secret.enc" -OutputFile "secret.txt"
安全建议
-
密钥管理:
- 使用强密码(至少12位,包含大小写字母、数字和特殊字符)
- 安全存储密钥文件
- 定期更换密钥
-
加密算法:
- 使用 AES-256 或更强的加密算法
- 使用 PBKDF2 进行密钥派生
- 添加 salt 防止彩虹表攻击
-
文件处理:
- 加密后安全删除原始文件
- 验证文件完整性
- 备份重要数据
这些脚本提供了完整的文件加密解密功能,可以根据你的需求选择合适的方法。