#!/usr/bin/env python
# -*-coding:utf-8-*-
"""
# File : Json文件加密解密.py
# Time :2022/6/30 22:58
# Author :Glad
# version :python 3.7.3
# Description:
"""
import json, random
from Crypto.Cipher import DES
def generate_random_str(randomlength=8):
"""
生成一个指定长度的随机字符串
"""
random_str = ''
base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
length = len(base_str) - 1
for i in range(randomlength):
random_str += base_str[random.randint(0, length)]
print("密钥key的值是:%s" % (random_str))
return random_str
def file_length(text):
"""
如果text不是8的倍数【加密文本text必须为8的倍数!】,补足为8的倍数
:param text:
:return: #padded_text:<class 'str'>
"""
while len(text) % 8 != 0:
text += ' '
return text
def dict2json(file_name, the_dict):
"""
将字典文件写如到json文件中
:param file_name: 要写入的json文件名(需要有.json后缀),str类型
:param the_dict: 要写入的数据,dict类型
:return: 1代表写入成功,0代表写入失败
"""
try:
json_str = json.dumps(the_dict, indent=4, ensure_ascii=False)
with open(file_name, 'w') as json_file:
json_file.write(json_str)
print("把字典数据写入json 文件,执行成功!!!")
return 1
except:
return 0
def data_type_conversion(json_path):
"""
Json文件转换成字符串
:param file_path:
:return:
"""
with open(json_path, "r") as f:
row_data = json.load(f) # 遍历json数据
info_str = json.dumps(row_data) # 字典转json字符串 <class 'str'>
return info_str
def file_encrypt(key,padded_text):
"""
文件加密
:param self:
:param text:
:return:
"""
des = DES.new(key, DES.MODE_ECB) # 创建DES实例
encrypted_text = des.encrypt(padded_text.encode('utf-8')) # 加密 #encrypted_text : <class 'bytes'>
print("Json文件加密的数据是: %s" % (encrypted_text))
return encrypted_text
def file_decrypt(key,encrypted_text):
"""
文件解密
:param self:
:param text:
:return:
"""
des = DES.new(key, DES.MODE_ECB) # 创建DES实例
plain_text = des.decrypt(encrypted_text).decode().rstrip('') # 解密 # plain_text: <class 'str'>
# dic_plain_text = ast.literal_eval(plain_text) # 字符串转字典 ,<class 'dict'>
dic_plain_text = json.loads(plain_text) # 字符串转字典 ,<class 'dict'>
print("Json文件解密的数据是: %s" % (dic_plain_text))
return dic_plain_text
if __name__ == '__main__':
row_data = {}
path = 'G:\\python_study\\com\\文件加密\\DES_文件加密\\service_account.json'
to_path = 'G:\\python_study\\com\\文件加密\\DES_文件加密\\service_account_new.json'
key_info = generate_random_str(8) # 密钥 8位或16位,必须为bytes
key = key_info.encode('UTF-8') # key的类型是:<class 'bytes'>
padded_text = file_length(data_type_conversion(path))
info_encrypt = file_encrypt(key,padded_text)
info_decrypt = file_decrypt(key,info_encrypt)
dict2json(to_path, info_decrypt)
Python 对json文件加密和解密
于 2022-07-01 09:22:54 首次发布