python gmssl SM4不填充加解密

问题描述

使用gmssl(python版本)进行SM4加/解密时结果与国标(GMT0002)不符,或解密失败,原因是gmssl默认使用PKCS7填充,国标文档里的样例是没有填充的。

解决方法

方法一:创建CryptSM4对象时将填充模式设为-1。这是笔者推荐的方法。

方法二:使用CryptSM4.one_round。这是个底层函数,每次只能加/解密一个分组。

例程

python 复制代码
from gmssl import sm4, func

g_sData = '0123456789abcdeffedcba9876543210'
g_sKey = '0123456789abcdeffedcba9876543210'


def main():
    bufData = bytes.fromhex(g_sData)
    bufKey = bytes.fromhex(g_sKey)

    oSM4 = sm4.CryptSM4()
    oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
    r = oSM4.crypt_ecb(bufData)
    print(f'enc:{r.hex()}')

    oSM4 = sm4.CryptSM4(sm4.SM4_ENCRYPT, sm4.PKCS7)
    oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
    r = oSM4.crypt_ecb(bufData)
    print(f'enc:{r.hex()}')

    oSM4 = sm4.CryptSM4(sm4.SM4_ENCRYPT, sm4.ZERO)
    oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
    r = oSM4.crypt_ecb(bufData)
    print(f'enc:{r.hex()}')

    oSM4 = sm4.CryptSM4(sm4.SM4_ENCRYPT, -1)  # 方法1
    oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
    r = oSM4.crypt_ecb(bufData)
    print(f'enc:{r.hex()}')
    oSM4.set_key(bufKey, sm4.SM4_DECRYPT)
    r = oSM4.crypt_ecb(r)
    print(f'dec:{r.hex()}')

    oSM4 = sm4.CryptSM4()  # 方法2
    oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
    r = oSM4.one_round(oSM4.sk, bufData)
    r = func.list_to_bytes(r)
    print(f'enc:{r.hex()}')
    oSM4.set_key(bufKey, sm4.SM4_DECRYPT)
    #r = func.bytes_to_list(r)
    r = oSM4.one_round(oSM4.sk, r)
    r = func.list_to_bytes(r)
    print(f'dec:{r.hex()}')

    return


if __name__ == '__main__':
    main()

例程输出:

enc:681edf34d206965e86b3e94f536e4246002a8a4efa863ccad024ac0300bb40d2

enc:681edf34d206965e86b3e94f536e4246002a8a4efa863ccad024ac0300bb40d2

enc:681edf34d206965e86b3e94f536e42462677f46b09c122cc975533105bd4a22a

enc:681edf34d206965e86b3e94f536e4246

dec:0123456789abcdeffedcba9876543210

enc:681edf34d206965e86b3e94f536e4246

dec:0123456789abcdeffedcba9876543210

注意事项

sm4.ZERO是一个名字叫"ZERO"的填充模式,不是不填充。

------完------

相关推荐
小九九的爸爸5 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学6 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉