首页 > 编程语言 >python 国密sm2(C1C3C2) sm4(CBC) 加密 解密

python 国密sm2(C1C3C2) sm4(CBC) 加密 解密

时间:2024-05-20 17:19:50浏览次数:24  
标签:CBC python crypt sm4 sm2 key inputText keycode

from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
import binascii
import base64
from gmssl import sm2, func
# GMSSL for Python
# 安装 pip install gmssl
#
keycode = '101231221289195374403401962572899'
key = '1012312212891953'
iv = '1012312262572899'
inputText = '{"key":"1012312212891953","iv":"1012312262572899","encryptText":"123456","inputType":"sm4-cbc","formatOut":"base64"}' #  bytes类型
private_key = 'CB772811F1FEF955CE1B4051130870D86CCA6AFEDE806F1E7C225D7359591D2B'
public_key = '0475E60AB5B94860DAD0C2D193551A8B7A628A611DF332E23DFCB42F6ECC348653B8A49418E52FF8872B500EEAF8BE8C43B7389D115E91B7432BB1C939E764D31A'
cipherMode = 1


keyBytes = key.encode()
ivBytes = iv.encode()
inputTextBytes = inputText.encode()

def ByteToHex( bins ):
    return ''.join( [ "%02X" % x for x in bins ] ).strip()

def HexToByte( hexStr ):
    return bytes.fromhex(hexStr)

#sm4CBC
crypt_sm4 = CryptSM4()
crypt_sm4.set_key(keyBytes, SM4_ENCRYPT)
encrypt_value = crypt_sm4.crypt_cbc(ivBytes , inputTextBytes) #  bytes类型

crypt_sm4.set_key(keyBytes, SM4_DECRYPT)
decrypt_value = crypt_sm4.crypt_cbc(ivBytes, encrypt_value)
decrypt_value = decrypt_value.decode('utf-8')
assert inputText == decrypt_value

#print("SM4CBC加密(bytes):",encrypt_value)
print("SM4CBC加密 (hex):",ByteToHex(encrypt_value))
print("SM4CBC加密 (base64):",base64.b64encode(encrypt_value))
print("SM4CBC解密(utf-8):",decrypt_value)

#sm2 cipherMode (c1c3c2)
sm2_crypt = sm2.CryptSM2(
    public_key = public_key,
    private_key = private_key,
    mode = cipherMode
)

enc_data = sm2_crypt.encrypt(inputTextBytes)
dec_data =sm2_crypt.decrypt(enc_data).decode('utf-8')
assert dec_data == dec_data

#print("SM2加密(bytes):",enc_data)
print("SM2加密 (hex):","04" + ByteToHex(enc_data))
print("SM2加密 (hex):","04" + enc_data.hex())
print("SM2解密(utf-8):",dec_data)

 

 

from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
import binascii
import base64
from gmssl import sm2, func

# GMSSL for Python
# 安装 pip install gmssl
# 封装函数

def sm2Encrypt(inputText, public_key, private_key, cipherMode = 1):
    inputTextBytes = inputText.encode()
    sm2_crypt = sm2.CryptSM2(
        public_key = public_key,
        private_key = private_key,
        mode = cipherMode
    )
    sm2EncryptData = sm2_crypt.encrypt(inputTextBytes)
    return '04' + sm2EncryptData.hex()

def sm4Encrypt(inputText, keycode):
    key = keycode[:16]
    iv = keycode[:8] + keycode[-8:]
    keyBytes = key.encode()
    ivBytes = iv.encode()
    inputTextBytes = inputText.encode()

    crypt_sm4 = CryptSM4()
    crypt_sm4.set_key(keyBytes, SM4_ENCRYPT)

    sm4EncryptData = crypt_sm4.crypt_cbc(ivBytes, inputTextBytes)  # bytes类型
    return base64.b64encode(sm4EncryptData).decode('utf-8')

def sm4Decrypt(inputText, keycode):
    key = keycode[:16]
    iv = keycode[:8] + keycode[-8:]
    keyBytes = key.encode()
    ivBytes = iv.encode()
    #inputTextBytes = inputText.encode()
    inputTextBytes = base64.b64decode(inputText)

    crypt_sm4 = CryptSM4()
    crypt_sm4.set_key(keyBytes, SM4_DECRYPT)

    sm4DecryptData = crypt_sm4.crypt_cbc(ivBytes, inputTextBytes)  # bytes类型
    return sm4DecryptData.decode('utf-8')

#sm2加密
inputText = '{"key":"1012312212891953","iv":"1012312262572899","encryptText":"123456","inputType":"sm4-cbc","formatOut":"base64"}' #  bytes类型
private_key = 'CB772811F1FEF955CE1B4051130870D86CCA6AFEDE806F1E7C225D7359591D2B'
public_key = '0475E60AB5B94860DAD0C2D193551A8B7A628A611DF332E23DFCB42F6ECC348653B8A49418E52FF8872B500EEAF8BE8C43B7389D115E91B7432BB1C939E764D31A'
sm2EncryptData = sm2Encrypt(inputText, public_key, private_key, cipherMode = 1)
print('sm2函数加密:',sm2EncryptData)

#sm4CBC加密
keycode = '101231221289195374403401962572899'
inputText = '{"key":"1012312212891953","iv":"1012312262572899","encryptText":"123456","inputType":"sm4-cbc","formatOut":"base64"}'
sm4EncryptData = sm4Encrypt(inputText, keycode)
print('sm4函数加密:',sm4EncryptData)

#sm4CBC解密
keycode = '101231221289195374403401962572899'
inputText = 'BHHr6W74yPnZEx4kFixG6bCTE7VJabZwANxpsh0G2cmd1ztFH5qSA7Qf1M6bxN4mh1wXxv0yDSO8sZnmvuH3XHNIiE7EaI+fxRsOQTcmZei5fKoaxSnT9ltv79VqSJ8D4m3YO5jiWOVEaJ+x5i8yx4iOWpcc5ZPhHT8Y6f8EP0o='

sm4EncryptData = sm4Decrypt(inputText, keycode)
print('sm4函数解密:',sm4EncryptData)

 

标签:CBC,python,crypt,sm4,sm2,key,inputText,keycode
From: https://www.cnblogs.com/zhouein/p/18202419

相关文章

  • Python-无服务器微服务构建指南-全-
    Python无服务器微服务构建指南(全)原文:zh.annas-archive.org/md5/3c97e70c885487f68835a4d0838eee09译者:飞龙协议:CCBY-NC-SA4.0前言这本书将让您对微服务和无服务器计算有很好的理解,以及它们与现有架构相比的优缺点。您将对部署完整的无服务器堆栈的威力有所认识,不仅在节......
  • python操作redis数据库
    官方文档https://redis.io/docs/latest/develop/connect/clients/python/仓库https://github.com/redis/redis-py安装库pipinstallredis普通连接r=redis.Redis(host='10.0.0.5',port=6379,decode_responses=True)decode_responses表示响应的结果是解码后的......
  • Python 将PowerPoint (PPT/PPTX) 转为HTML
    PPT是传递信息、进行汇报和推广产品的重要工具。然而,有时我们需要将这些精心设计的PPT演示文稿发布到网络上,以便于更广泛的访问和分享。本文将介绍如何使用Python将PowerPoint文档转换为网页友好的HTML格式。包含两个简单示例:Python将PowerPoint文档转为HTML格式Python将指定......
  • python requests get请求 如何获取所有请求
    在Python中,使用requests库发送HTTPGET请求非常简单。如果你想获取所有的请求,通常意味着你想记录或跟踪这些请求。这可以通过使用requests的Session对象和自定义的HTTPAdapter来实现。以下是一个如何实现这一功能的示例代码:importrequestsfromrequests.adaptersimportHTTP......
  • 食物识别系统Python+深度学习人工智能+TensorFlow+卷积神经网络算法模型
    一、介绍食物识别系统。该项目通过构建包含11种常见食物类别(包括'Bread','Dairyproduct','Dessert','Egg','Friedfood','Meat','Noodles-Pasta','Rice','Seafood','Soup','Vegeta......
  • [998] Python unpacking operators (* and **)
    ref:Pythonunpackingoperators(*and**)(RECOMMENDED)ref:PythonFunctionsref:PythonUnpackDictionary:AComprehensiveGuideHerearesomecrucialthingsfortake-awayofthe unpackingoperators:Asingleasterisk * unpacksitemsfromlists,tupl......
  • python去除图片白边黑边
    主要用于去除图片的白边和黑边,比如在截图表情包的时候,通过小米的传送门保存图片的时候,图片往往会有黑边和白边,此时使用此脚本二次处理importosfromPILimportImage,ImageChopsdeftrim_white_border(image):bg=Image.new(image.mode,image.size,image.getpixel((0......
  • Python内置库:pathlib(文件路径操作)
    官方文档:pathlib—Object-orientedfilesystempaths一、基础使用遍历子目录使用通配符遍历文件拼接路径获取标准化后的绝对路径查询路径常规属性打开文件frompathlibimportPathprint('1.1查询指定目录的子目录')p=Path('D:/Envs')print([sub_pforsub_p......
  • 【PYTHON3】环境搭建+编程学习之路的开始——Windows系统
    一、概述在学习python开发语言之前需要安装好开发语言环境(也就是常说的开发环境)开发环境主要有:解释器和编辑器IDE,而其中的解释器是用来将代码转换成机器语言,python语言也就是解释器;编辑器用来写代码逻辑,python语言推荐的是pycharm,它是IDE集成开发环境,这里面有开发时需要的工具......
  • 【开源】2024最新python豆瓣电影数据爬虫+可视化分析项目
    项目介绍【开源】项目基于python+pandas+flask+mysql等技术实现豆瓣电影数据获取及可视化分析展示,觉得有用的朋友可以来个一键三连,感谢!!!项目演示[video(video-C9B87WwE-1716106102936)(type-bilibili)(url-https://player.bilibili.com/player.html?aid=1204518067)(image-https......