Skip to main content

Python SM4

Project description

pysm4

SM4算法

国密SM4(无线局域网SMS4)算法, 一个分组算法, 分组长度为128bit, 密钥长度为128bit, 算法具体内容参照SM4算法

pysm4

pysm4是国密SM4算法的Python实现, 提供了encryptdecryptencrypt_ecbdecrypt_ecbencrypt_cbcdecrypt_cbc等函数用于加密解密, 用法如下:

1. encryptdecrypt

>>> from pysm4 import encrypt, decrypt
# 明文
>>> clear_num = 0x0123456789abcdeffedcba9876543210
# 密钥
>>> mk = 0x0123456789abcdeffedcba9876543210
# 加密
>>> cipher_num = encrypt(clear_num, mk)
>>> hex(cipher_num)[2:].replace('L', '')
'681edf34d206965e86b3e94f536e4246'
# 解密
>>> clear_num == decrypt(cipher_num, mk)
True

2. encrypt_ecbdecrypt_ecb

>>> from pysm4 import encrypt_ecb, decrypt_ecb
# 明文
>>> plain_text = 'pysm4是国密SM4算法的Python实现'
# 密钥
>>> key = 'hello, world!'  # 密钥长度小于等于16字节
# 加密
>>> cipher_text = encrypt_ecb(plain_text, key)
>>> cipher_text
'ng3L4ldgvsZciAgx3LhplDvIzrd0+GXiNqNmd1VW0YOlwo+ojtpownOCbnxbq/3y'
# 解密
>>> plain_text == decrypt_ecb(cipher_text, key)
True

3. encrypt_cbcdecrypt_cbc

>>> from pysm4 import encrypt_cbc, decrypt_cbc
# 明文
>>> plain_text = 'pysm4是国密SM4算法的Python实现'
# 密钥
>>> key = 'hello, world!'  # 密钥 长度小于等于16字节
# 初始化向量
>>> iv = '11111111'        # 初始化向量  长度小于等于16字节
# 加密
>>> cipher_text = encrypt_cbc(plain_text, key, iv)
'cTsdKRSH2FqIJf22NHMjX5ZFHghR4ZtJ10wbNwj2//bJSElBXVeMtFycjdlVKP15'
# 解密
>>> plain_text == decrypt_cbc(cipher_text, key, iv)
True

pysm4实现了分组密码工作模式中的ECB(电子密码本)和CBC(密码块链接)模式, 具体内容请参考维基百科的分组密码工作模式

安装

GitHub

$ python setup.py install

PyPI

$ pip install pysm4

兼容

pysm4支持Python2.7和Python3.3以上版本,其他版本没有测试。

性能

验证SM4算法中的实例二:

实例二: 利用相同加密密钥对一组明文反复加密1000000次
明文: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10
密钥: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10 
密文: 59 52 98 c7 c6 fd 27 1f 04 02 f8 04 c3 3d 3f 66

使用pysm4在我个人电脑验证实例二时,耗时600多秒。性能比使用JAVA或C/C++实现版本差了很多。

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pysm4-0.7.2.tar.gz (8.1 kB view hashes)

Uploaded Source

Built Distribution

pysm4-0.7.2-py3-none-any.whl (8.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page