商密2(SM2)获取公私钥对、加解密文件
exe文件下载
链接: https://pan.baidu.com/s/1OAPvcv26NoVpmmXM7kq_xQ?pwd=c46d 提取码: c46d
以下为源代码:
获取SM2公私钥对
import os
import time
from gmssl import sm2
def generate_key_pair():
# 生成32字节(256位)的私钥
pri_key = os.urandom(32).hex()
# 使用gmssl生成公钥
sm2_crypt = sm2.CryptSM2(private_key=pri_key, public_key='')
pub_key = sm2_crypt._kg(int(pri_key, 16), sm2.default_ecc_table['g'])
return pri_key, pub_key
if __name__ == '__main__':
pri_key, pub_key =generate_key_pair()
with open('key_pair_' + str(time.time()) + '.txt', 'w') as f:
f.write('公钥:' + pub_key + '\n私钥:' + pri_key)
SM2加密文件
from gmssl import sm2
def encrypt_file(file_path, pub_key):
# 读取文件内容
with open(file_path, 'rb') as f:
data = f.read()
# 初始化SM2加密对象
sm2_crypt = sm2.CryptSM2(public_key=pub_key, private_key='', mode=1, asn1=True)
# 加密数据
print('开始加密:', file_path)
encrypted_data = sm2_crypt.encrypt(data)
# 将加密结果写入新文件
encrypted_file_path = file_path + '.encrypted'
with open(encrypted_file_path, 'wb') as f:
f.write(encrypted_data)
return encrypted_file_path
if __name__ == '__main__':
file_path = input('请输入需要加密的文件:')
pub_key = input('请输入SM2公钥:')
# 加密文件
encrypted_file = encrypt_file(file_path, pub_key)
print('加密后的文件:', encrypted_file)
SM2解密文件
from gmssl import sm2
def decrypt_file(encrypted_file_path, pri_key):
# 读取加密文件内容
with open(encrypted_file_path, 'rb') as f:
encrypted_data = f.read()
# 初始化SM2解密对象
sm2_crypt = sm2.CryptSM2(private_key=pri_key, public_key='', mode=1, asn1=True)
# 解密数据
print('开始解密:', encrypted_file_path)
decrypted_data = sm2_crypt.decrypt(encrypted_data)
# 将解密结果写入新文件
decrypted_file_path = encrypted_file_path.replace('.encrypted', '.decrypted.' + encrypted_file_path.split('.')[-2])
with open(decrypted_file_path, 'wb') as f:
f.write(decrypted_data)
return decrypted_file_path
if __name__ == "__main__":
file_path = input('请输入需要解密的文件:')
pri_key = input('请输入与SM2公钥对应的私钥:')
# 解密文件
decrypted_file = decrypt_file(file_path, pri_key)
print("解密后的文件:", decrypted_file)

浙公网安备 33010602011771号