GMSSL: China's National Cryptographic Algorithms
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
-
ModuleNotFoundError: No module named 'gmssl'
cause The `gmssl` library is not installed in the current Python environment.fixRun `pip install gmssl` to install the library. -
ValueError: key is not 16 bytes
cause The SM4 key provided for encryption/decryption does not have the required length of 16 bytes.fixEnsure the key variable is a `bytes` object exactly 16 bytes long. For example, `key = b'mysecretkey12345'`. -
TypeError: argument should be bytes or other byte-like object, not str
cause A string (`str`) was passed to a cryptographic function that expects byte-like objects (`bytes`).fixConvert the string to bytes using `.encode('utf-8')` or ensure string literals are byte literals (e.g., `b'data'`).
Warnings
- gotcha All cryptographic inputs (keys, IVs, data) and outputs must be `bytes`. Passing `str` will result in a `TypeError`.
- gotcha SM4 keys and IVs must be exactly 16 bytes long. Providing an incorrect length will raise a `ValueError`.
- gotcha As a pure-Python implementation, `gmssl` might exhibit lower performance for high-throughput cryptographic operations compared to C-accelerated libraries.
Install
-
pip install gmssl
Imports
- sm2
from gmssl import sm2
- sm3
from gmssl import sm3
- sm4
from gmssl import sm4
Quickstart
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.")