如何写一个脚本简易加密文件

wen 实用脚本 2

本文目录导读:

如何写一个脚本简易加密文件

  1. 使用 openssl(最推荐)
  2. Python 简易加密脚本
  3. Windows Batch 简易加密脚本
  4. 安装依赖
  5. 使用方法
  6. 增强建议

使用 openssl(最推荐)

Linux/Mac 加密脚本

#!/bin/bash
# encrypt.sh - 简易文件加密脚本
# 加密函数
encrypt_file() {
    local input_file=$1
    local output_file="${input_file}.enc"
    echo "请输入加密密码:"
    read -s password
    openssl enc -aes-256-cbc -salt -in "$input_file" -out "$output_file" -pass pass:"$password"
    if [ $? -eq 0 ]; then
        echo "加密成功!输出文件: $output_file"
        rm "$input_file"  # 可选:删除原文件
    else
        echo "加密失败!"
    fi
}
# 解密函数
decrypt_file() {
    local input_file=$1
    local output_file="${input_file%.enc}"
    echo "请输入解密密码:"
    read -s password
    openssl enc -d -aes-256-cbc -in "$input_file" -out "$output_file" -pass pass:"$password"
    if [ $? -eq 0 ]; then
        echo "解密成功!输出文件: $output_file"
    else
        echo "解密失败!密码错误或文件损坏"
    fi
}
# 主程序
echo "文件加密工具"
echo "1. 加密文件"
echo "2. 解密文件"
read -p "请选择操作 (1/2): " choice
case $choice in
    1)
        read -p "请输入要加密的文件: " file
        encrypt_file "$file"
        ;;
    2)
        read -p "请输入要解密的文件: " file
        decrypt_file "$file"
        ;;
    *)
        echo "无效选择"
        ;;
esac

Python 简易加密脚本

#!/usr/bin/env python3
# simple_encrypt.py
import os
import sys
import base64
import getpass
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def get_key(password, salt):
    """通过密码生成密钥"""
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
    )
    key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
    return key
def encrypt_file(file_path):
    """加密文件"""
    password = getpass.getpass("请输入加密密码: ")
    confirm = getpass.getpass("确认密码: ")
    if password != confirm:
        print("密码不匹配!")
        return
    # 生成随机盐值
    salt = os.urandom(16)
    key = get_key(password, salt)
    f = Fernet(key)
    try:
        # 读取原文件
        with open(file_path, 'rb') as file:
            file_data = file.read()
        # 加密数据
        encrypted_data = f.encrypt(file_data)
        # 写入加密文件(包含盐值)
        output_path = file_path + '.enc'
        with open(output_path, 'wb') as file:
            file.write(salt + encrypted_data)
        print(f"加密成功!输出: {output_path}")
        # 可选:删除原文件
        # os.remove(file_path)
    except Exception as e:
        print(f"加密失败: {e}")
def decrypt_file(file_path):
    """解密文件"""
    password = getpass.getpass("请输入解密密码: ")
    try:
        # 读取加密文件
        with open(file_path, 'rb') as file:
            # 前16字节是盐值
            salt = file.read(16)
            encrypted_data = file.read()
        # 生成密钥
        key = get_key(password, salt)
        f = Fernet(key)
        # 解密数据
        decrypted_data = f.decrypt(encrypted_data)
        # 写入解密文件
        output_path = file_path.replace('.enc', '.dec')
        with open(output_path, 'wb') as file:
            file.write(decrypted_data)
        print(f"解密成功!输出: {output_path}")
    except Exception as e:
        print(f"解密失败: {e}")
def main():
    if len(sys.argv) < 2:
        print("用法: python simple_encrypt.py <文件名>")
        print("      python simple_encrypt.py -d <加密文件名>")
        return
    if sys.argv[1] == '-d':
        if len(sys.argv) < 3:
            print("请指定要解密的文件")
            return
        decrypt_file(sys.argv[2])
    else:
        encrypt_file(sys.argv[1])
if __name__ == "__main__":
    main()

Windows Batch 简易加密脚本

@echo off
chcp 65001 >nul文件加密工具
:menu
cls
echo ========== 文件加密工具 ==========
echo 1. 加密文件
echo 2. 解密文件
echo 3. 退出
echo ================================
set /p choice=请选择操作:
if "%choice%"=="1" goto encrypt
if "%choice%"=="2" goto decrypt
if "%choice%"=="3" exit
goto menu
:encrypt
cls
set /p file=请输入要加密的文件路径:
set /p password=请输入密码:
certutil -encode "%file%" "%file%.b64" >nul
choice /c YN /m "是否删除原文件?"
if errorlevel 2 goto no_del
del "%file%"
:no_del
echo 加密完成!文件已保存为 %file%.b64
pause
goto menu
:decrypt
cls
set /p file=请输入要解密的文件(.b64):
set /p password=请输入密码:
set dname=%file:.b64=%
certutil -decode "%file%" "%dname%" >nul
echo 解密完成!
pause
goto menu

安装依赖

Python 版本需要安装依赖:

pip install cryptography

使用方法

Shell 脚本:

chmod +x encrypt.sh
./encrypt.sh

Python 脚本:

# 加密
python simple_encrypt.py myfile.txt
# 解密
python simple_encrypt.py -d myfile.txt.enc

增强建议

  1. 添加错误处理
  2. 支持批量加密
  3. 增加进度显示
  4. 保存加密日志
  5. 支持更多加密算法

这些脚本提供了基础的加密功能,适合日常使用,对于重要数据,建议使用专业的加密软件。

抱歉,评论功能暂时关闭!