(python)对文件进行加密和解密

前言

        在 Python 中,可以使用加密算法来对配置文件内容进行加密和解密。

         一种常用的方法是使用对称加密算法,例如AES(高级加密标准)。

目录

相关第三方库

安装指令

异常处理

代码示例


相关第三方库

  • Crypto
  • base64

安装指令

pip install pycryptodome
异常处理

若安装好之后,仍然提示模块不存在,请卸载旧的第三方库pycrypto再重新安装.

代码示例

import base64

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad


# 加密函数
def func_encrypt_config(_key, plain_text):
    cipher = AES.new(_key, AES.MODE_CBC)
    ciphertext = cipher.encrypt(pad(plain_text.encode(), AES.block_size))
    iv = base64.b64encode(cipher.iv).decode()
    encrypted_text = base64.b64encode(ciphertext).decode()
    return iv + encrypted_text


# 解密函数
def func_decrypt_config(_key, encrypted_text):
    iv = base64.b64decode(encrypted_text[:24])
    ciphertext = base64.b64decode(encrypted_text[24:])
    cipher = AES.new(_key, AES.MODE_CBC, iv)
    decrypted_text = unpad(cipher.decrypt(ciphertext), AES.block_size).decode()
    return decrypted_text


# 配置文件明文内容
config_content = """
[Database]
host = localhost
port = 8888
username = root
password = 88888888
"""

# 加密配置文件内容
key = b'mysecretpassword'  # 密钥(需要确保安全)
encrypted_content = func_encrypt_config(key, config_content)
print("加密后的配置文件内容:")
print(encrypted_content)

# 解密配置文件内容
decrypted_content = func_decrypt_config(key, encrypted_content)
print("解密后的配置文件内容:")
print(decrypted_content)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Marst·Zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值