Commit 036dae71 by liuqingjun2

添加加密的模型处理文件

parent d6511d13
import os
import base64
import marshal
import zlib
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
# 加密配置
PASSWORD = b'wangbing666' # 加密密码
SALT = b'salt_12345' # 加密盐值
def generate_key():
"""生成加密密钥"""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=SALT,
iterations=100000,
)
key = base64.urlsafe_b64encode(kdf.derive(PASSWORD))
return key
def encrypt_py_file(source_file, target_file, key):
"""
加密Python文件并保存为.pyc格式
"""
# 读取源代码
with open(source_file, 'rb') as f:
source = f.read()
# 编译源代码
try:
code = compile(source, source_file, 'exec')
# 序列化代码对象
marshalled = marshal.dumps(code)
# 压缩
compressed = zlib.compress(marshalled)
# 加密
f = Fernet(key)
encrypted = f.encrypt(compressed)
# 写入加密后的数据
with open(target_file, 'wb') as f:
# 写入魔数和时间戳(与标准.pyc文件格式一致)
f.write(b'\x6f\x0d\x0d\x0a') # 魔数
f.write(b'\x00' * 12) # 时间戳和文件大小(占位)
f.write(encrypted) # 加密后的数据
print(f"已加密: {source_file} -> {target_file}")
return True
except Exception as e:
print(f"加密 {source_file} 时出错: {e}")
return False
def update_gitignore(files):
"""更新.gitignore文件,添加要忽略的源文件"""
gitignore = '.gitignore'
to_ignore = [f for f in files if os.path.exists(f)]
if not to_ignore:
return
# 读取现有的.gitignore内容
existing = set()
if os.path.exists(gitignore):
with open(gitignore, 'r', encoding='utf-8') as f:
existing = set(line.strip() for line in f if line.strip() and not line.startswith('#'))
# 添加新条目
new_entries = set(to_ignore)
all_entries = existing.union(new_entries)
# 写回.gitignore
with open(gitignore, 'w', encoding='utf-8') as f:
f.write("# 加密源文件\n")
f.write("\n".join(sorted(all_entries)))
f.write("\n")
print("\n已更新 .gitignore 文件")
def main():
# 要加密的文件列表
files_to_encrypt = [
'handlers/modelpage/model_training_handler.py',
'handlers/modelpage/model_test_handler.py',
'handlers/modelpage/training_handler.py',
'handlers/modelpage/model_trainingworker_handler.py'
]
# 生成加密密钥
key = generate_key()
# 创建加密文件
for file in files_to_encrypt:
if os.path.exists(file):
target_file = file + 'c' # 添加c扩展名
encrypt_py_file(file, target_file, key)
else:
print(f"文件不存在: {file}")
# 更新.gitignore文件
update_gitignore(files_to_encrypt)
print("\n加密完成!请确保安全保存加密密钥。")
if __name__ == "__main__":
main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment