GMSSL: China's National Cryptographic Algorithms

3.2.2 · active · verified Fri Apr 17

GMSSL is a pure-Python library providing implementations of China's national cryptographic algorithms: SM2 (elliptic curve cryptography), SM3 (hash function), and SM4 (block cipher). It is currently at version 3.2.2 and is actively maintained, with releases typically following bug fixes or minor enhancements.

Common errors

Warnings

Install

Imports

Quickstart

Encrypts and decrypts data using SM4 in both ECB and CBC modes, demonstrating the required `bytes` input for keys, IVs, and data. The library automatically handles PKCS7 padding for `encrypt` and removes it for `decrypt`.

from gmssl import sm4

# SM4 operates on 16-byte blocks with a 16-byte key.
key = b'this is a 16-byt' # Must be 16 bytes
iv = b'this is a 16-byt'  # Must be 16 bytes for CBC mode

# Example for ECB mode (no IV needed, but data must be padded/block aligned)
# gmssl.sm4.encrypt/decrypt handles PKCS7 padding automatically if not block-aligned.
original_data_ecb = b'Hello world! This is a test message for SM4 ECB mode.'
encrypted_ecb = sm4.encrypt(key, original_data_ecb)
decrypted_ecb = sm4.decrypt(key, encrypted_ecb)
assert original_data_ecb == decrypted_ecb
print(f"SM4 ECB: Original: {original_data_ecb}, Decrypted: {decrypted_ecb}")

# Example for CBC mode (IV required)
original_data_cbc = b'Another test message for SM4 CBC mode, with an IV.'
encrypted_cbc = sm4.encrypt(key, original_data_cbc, iv)
decrypted_cbc = sm4.decrypt(key, encrypted_cbc, iv)
assert original_data_cbc == decrypted_cbc
print(f"SM4 CBC: Original: {original_data_cbc}, Decrypted: {decrypted_cbc}")

print("SM4 encryption/decryption examples completed successfully.")

view raw JSON →