使用lib.config实现配置文件加密和解密
在Python中,我们可以使用configparser库来读取和写入配置文件。但是,configparser库并没有提供配置文件的加密和解密功能。如果我们希望在配置文件中存储敏感信息(如数据库密码)时进行加密,可以使用pycryptodome库来实现。
首先,我们需要安装pycryptodome库。可以使用以下命令来安装:
pip install pycryptodome
接下来,我们可以创建一个config.ini配置文件,其中包含需要加密的敏感信息。例如:
[database] host = localhost port = 3306 username = myusername password = mypassword
然后,我们可以创建一个名为lib_config.py的Python文件,其中包含加密和解密配置文件的代码。具体的代码实现如下所示:
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
import configparser
def encrypt(key, filename):
chunk_size = 64 * 1024
output_file = f"{filename}.enc"
iv = Random.new().read(AES.block_size)
encryptor = AES.new(SHA256.new(key.encode()).digest(), AES.MODE_CBC, iv)
with open(filename, 'rb') as file:
with open(output_file, 'wb') as encrypted_file:
encrypted_file.write(iv)
while True:
chunk = file.read(chunk_size)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b' ' * (16 - (len(chunk) % 16))
encrypted_file.write(encryptor.encrypt(chunk))
return output_file
def decrypt(key, filename):
chunk_size = 64 * 1024
output_file = f"{filename[:-4]}"
with open(filename, 'rb') as encrypted_file:
iv = encrypted_file.read(AES.block_size)
decryptor = AES.new(SHA256.new(key.encode()).digest(), AES.MODE_CBC, iv)
with open(output_file, 'wb') as decrypted_file:
while True:
chunk = encrypted_file.read(chunk_size)
if len(chunk) == 0:
break
decrypted_file.write(decryptor.decrypt(chunk))
decrypted_file.truncate()
return output_file
def read_config(filename):
config = configparser.ConfigParser()
config.read(filename)
return config
def write_config(filename, config):
with open(filename, 'w') as file:
config.write(file)
# 使用示例
key = "mysecretkey"
# 加密配置文件
encrypted_file = encrypt(key, "config.ini")
print("配置文件已加密:", encrypted_file)
# 解密配置文件
decrypted_file = decrypt(key, encrypted_file)
print("配置文件已解密:", decrypted_file)
# 读取解密后的配置文件
config = read_config(decrypted_file)
# 打印配置信息
print("数据库主机:", config.get('database', 'host'))
print("数据库端口:", config.get('database', 'port'))
print("用户名:", config.get('database', 'username'))
print("密码:", config.get('database', 'password'))
# 更新配置信息
config.set('database', 'password', 'newpassword')
# 写入更新后的配置文件
write_config(decrypted_file, config)
# 重新加密配置文件
encrypted_file = encrypt(key, decrypted_file)
print("配置文件已重新加密:", encrypted_file)
上述代码中,我们使用AES算法和SHA256散列函数来加密和解密配置文件。首先,我们定义了一个encrypt函数,它接受一个密钥和配置文件名作为输入,然后将配置文件加密后保存为.enc文件。同样地,我们也定义了一个decrypt函数,它接受一个密钥和已加密的配置文件名作为输入,然后将配置文件解密后保存。另外,我们还定义了read_config函数和write_config函数,分别用于读取和写入配置信息。
在示例代码中,我们使用了一个名为config.ini的配置文件,并使用了一个名为mysecretkey的密钥。首先,我们调用encrypt函数将配置文件加密,并保存为.enc文件。然后,我们调用decrypt函数将加密后的配置文件解密,并保存为原始的配置文件。接下来,我们使用read_config函数读取解密后的配置文件,并打印了数据库的主机、端口、用户名和密码等信息。然后,我们更新了配置文件中的密码,并使用write_config函数写入更新后的配置文件。最后,我们再次调用encrypt函数重新加密配置文件。
总结起来,通过使用pycryptodome库,我们可以方便地实现配置文件的加密和解密功能,从而可以更安全地存储和传输敏感信息。
