### Compile and Install GmSSL Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Steps to compile and install the GmSSL library from source code using CMake and Make. ```bash mkdir build cd build cmake .. make make test sudo make install ``` -------------------------------- ### Install gmssl-python from Source Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Installs the gmssl-python package locally from downloaded source code using pip. ```bash pip install . pip show gmssl-python ``` -------------------------------- ### Install GmSSL Python Package from Source Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Clones the GmSSL-Python repository, runs unit tests to verify the build, and then installs the package locally. ```bash git clone https://github.com/GmSSL/GmSSL-Python.git cd GmSSL-Python python -m unittest -v # Run tests to verify build pip install . ``` -------------------------------- ### Check GmSSL Installation Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Verifies the GmSSL installation by running the 'gmssl' command-line tool. ```bash gmssl help ``` -------------------------------- ### SM4-CBC Example Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Example demonstrating the encryption and decryption process using the Sm4Cbc class. ```APIDOC ## SM4-CBC Example ### Description Example demonstrating the encryption and decryption process using the Sm4Cbc class. ### Code Example ```python from gmssl import Sm4Cbc, SM4_KEY_SIZE, SM4_CBC_IV_SIZE, rand_bytes, DO_ENCRYPT, DO_DECRYPT key = rand_bytes(SM4_KEY_SIZE) iv = rand_bytes(SM4_CBC_IV_SIZE) plaintext = b'Hello, World!' # Encrypt enc = Sm4Cbc(key, iv, DO_ENCRYPT) ciphertext = enc.update(plaintext) ciphertext += enc.finish() # Decrypt dec = Sm4Cbc(key, iv, DO_DECRYPT) decrypted = dec.update(ciphertext) decrypted += dec.finish() assert decrypted == plaintext ``` ``` -------------------------------- ### Install GmSSL and gmssl-python Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/README.md Installs the GmSSL library and the gmssl-python package. Ensure GmSSL version 3.1.1 or higher and Python 3.7 or higher are installed. ```bash # Install GmSSL (see configuration.md for details) sudo apt-get install build-essential cmake git clone https://github.com/guanzhi/GmSSL.git cd GmSSL && mkdir build && cd build cmake .. && make && sudo make install # Install gmssl-python pip install gmssl-python # Verify python -c "import gmssl; print(gmssl.GMSSL_LIBRARY_VERSION)" ``` -------------------------------- ### Install GmSSL Python Package from PyPI Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Installs the gmssl-python package using pip, the standard Python package installer. ```bash pip install gmssl-python ``` -------------------------------- ### Compile and Install GmSSL Native Library Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Downloads, compiles, and installs the native GmSSL C library. Ensure you are in the GmSSL-master directory after downloading and unzipping. ```bash wget https://github.com/guanzhi/GmSSL/archive/refs/heads/master.zip unzip GmSSL-master.zip cd GmSSL-master mkdir build && cd build cmake .. make sudo make install sudo ldconfig gmssl help ``` -------------------------------- ### Full SM9 Signature Example Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Demonstrates the complete SM9 signature workflow, including key generation, signing, and verification. This example covers both the authority and user sides for signing and verification processes. ```python from gmssl import Sm9SignMasterKey, Sm9Signature, DO_SIGN, DO_VERIFY # Authority side: generate master key and user keys master = Sm9SignMasterKey() master.generate_master_key() master.export_encrypted_master_key_info_pem('sign_msk.pem', 'password') master.export_public_master_key_pem('sign_mpk.pem') # Generate key for Alice alice_key = master.extract_key('Alice') alice_key.export_encrypted_private_key_info_pem('alice_sign_key.pem', 'alice_password') # Signing side: Alice signs a message alice_sign_key = Sm9SignMasterKey() alice_sign_key.import_encrypted_master_key_info_pem('sign_msk.pem', 'password') alice_key = alice_sign_key.extract_key('Alice') message = b'Important message' signer = Sm9Signature(DO_SIGN) signer.update(message) signature = signer.sign(alice_key) # Verification side: verify Alice's signature using only her identity master_pub = Sm9SignMasterKey() master_pub.import_public_master_key_pem('sign_mpk.pem') verifier = Sm9Signature(DO_VERIFY) verifier.update(message) is_valid = verifier.verify(signature, master_pub, 'Alice') ``` -------------------------------- ### SM9 Encryption Decryption Example Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Example demonstrating how to import an encrypted SM9 user key and use it to decrypt a ciphertext. ```python from gmssl import Sm9EncMasterKey # User receives their key key = Sm9EncKey('alice@example.com') key.import_encrypted_private_key_info_pem('alice_key.pem', 'alice_password') # Decrypt a message ciphertext = b'...' # Replace with actual ciphertext plaintext = key.decrypt(ciphertext) ``` -------------------------------- ### Install GmSSL Build Tools (Ubuntu/Debian) Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Installs necessary build tools like GCC and CMake for compiling GmSSL on Ubuntu/Debian systems. ```bash sudo install build-essentials cmake ``` -------------------------------- ### Install GmSSL Native Library Dependencies on Ubuntu/Debian Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Installs the required build tools and libraries for compiling the GmSSL native library on Ubuntu or Debian-based systems. ```bash sudo apt-get install build-essential cmake ``` -------------------------------- ### SM3 Hashing Example Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Demonstrates how to compute the SM3 hash of a byte string using the Sm3 class. ```python from gmssl import * sm3 = Sm3() sm3.update(b'abc') dgst = sm3.digest() print("sm3('abc') : " + dgst.hex()) ``` -------------------------------- ### SM2 Signature Example: Signing and Verification Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/asymmetric.md Demonstrates the complete lifecycle of SM2 signature generation and verification. This includes generating a key pair, creating a signer with signing mode, updating message data, signing, and then verifying the signature using the public key. It also shows how to import a public key from a PEM file. ```python from gmssl import Sm2Key, Sm2Signature, DO_SIGN, DO_VERIFY # Signing side key = Sm2Key() key.generate_key() signer = Sm2Signature(key, 'Alice', DO_SIGN) signer.update(b'message') signature = signer.sign() # Verification side pub_key = Sm2Key() pub_key.import_public_key_info_pem('alice_pub.pem') verifier = Sm2Signature(pub_key, 'Alice', DO_VERIFY) verifier.update(b'message') is_valid = verifier.verify(signature) ``` -------------------------------- ### Install GmSSL Native Library Dependencies on macOS Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Installs CMake using Homebrew, a prerequisite for compiling the native GmSSL library on macOS. ```bash brew install cmake ``` -------------------------------- ### Install GmSSL Native Library Dependencies on CentOS/RHEL Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Installs the necessary development tools and CMake for compiling the GmSSL native library on CentOS or RHEL systems. ```bash sudo yum groupinstall "Development Tools" sudo yum install cmake ``` -------------------------------- ### SM4-GCM Encryption and Decryption Example Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Demonstrates how to use the Sm4Gcm class for both encrypting and decrypting data with an authentication tag. Ensure you have the necessary imports and generate random keys and IVs for security. ```python from gmssl import Sm4Gcm, SM4_KEY_SIZE, SM4_GCM_DEFAULT_IV_SIZE, rand_bytes, DO_ENCRYPT, DO_DECRYPT key = rand_bytes(SM4_KEY_SIZE) iv = rand_bytes(SM4_GCM_DEFAULT_IV_SIZE) aad = b'protocol_header' plaintext = b'sensitive_data' # Encrypt gcm_enc = Sm4Gcm(key, iv, aad, taglen=16, encrypt=DO_ENCRYPT) ciphertext = gcm_enc.update(plaintext) ciphertext += gcm_enc.finish() # ciphertext now contains: encrypted_data || authentication_tag # Decrypt gcm_dec = Sm4Gcm(key, iv, aad, taglen=16, encrypt=DO_DECRYPT) decrypted = gcm_dec.update(ciphertext) decrypted += gcm_dec.finish() assert decrypted == plaintext ``` -------------------------------- ### Verify GmSSL-Python Installation Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Checks the installed gmssl-python and libgmssl versions within a Python interpreter. ```python import gmssl gmssl.GMSSL_PYTHON_VERSION gmssl.GMSSL_LIBRARY_VERSION ``` -------------------------------- ### Hash Data with SM3 Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/README.md Demonstrates how to compute the SM3 hash of a message. Ensure the gmssl library is installed. ```python from gmssl import Sm3 sm3 = Sm3() sm3.update(b'message') dgst = sm3.digest() print(dgst.hex()) ``` -------------------------------- ### Verify GmSSL Python Installation Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Checks the installed GmSSL Python wrapper version and the linked GmSSL native library version. The native library version should be 3.1.1 or later. ```python import gmssl print(gmssl.GMSSL_PYTHON_VERSION) # Should print: 2.2.2 print(gmssl.GMSSL_LIBRARY_VERSION) # Should print: 3.1.1 or later ``` -------------------------------- ### SM2 Signature Example: Incremental Updates and Verification Failure Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/asymmetric.md Illustrates the use of incremental updates for message data with the SM2 signature API. It shows signing a message in chunks, verifying a correct signature, and then demonstrating that verification fails when the message content is altered. ```python from gmssl import Sm2Key, Sm2Signature, DO_SIGN, DO_VERIFY key = Sm2Key() key.generate_key() # Sign a message signer = Sm2Signature(key, 'Signer', DO_SIGN) signer.update(b'Hello ') signer.update(b'World!') sig = signer.sign() # Verify the same message verifier = Sm2Signature(key, 'Signer', DO_VERIFY) verifier.update(b'Hello ') verifier.update(b'World!') assert verifier.verify(sig) # Different message fails verification verifier2 = Sm2Signature(key, 'Signer', DO_VERIFY) verifier2.update(b'Hello Evil!') assert not verifier2.verify(sig) ``` -------------------------------- ### Complete SM9 Signature Workflow Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Illustrates the SM9 signature process, covering master key setup, key extraction, message signing, and signature verification. Verification only requires the public master key and the signer's ID. ```python from gmssl import Sm9SignMasterKey, Sm9Signature, DO_SIGN, DO_VERIFY # Authority: Setup master = Sm9SignMasterKey() master.generate_master_key() master.export_encrypted_master_key_info_pem('sign_msk.pem', 'password') master.export_public_master_key_pem('sign_mpk.pem') alice_key = master.extract_key('Alice') # Alice: Sign a message signer = Sm9Signature(DO_SIGN) signer.update(b'Important message') signature = signer.sign(alice_key) # Bob: Verify (no Alice key needed, only system public key and her ID) master_pub = Sm9SignMasterKey() master_pub.import_public_master_key_pem('sign_mpk.pem') verifier = Sm9Signature(DO_VERIFY) verifier.update(b'Important message') is_valid = verifier.verify(signature, master_pub, 'Alice') ``` -------------------------------- ### Handle NativeError During Key Import Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/types.md Example of catching NativeError when importing an encrypted private key with an incorrect password. This demonstrates practical error handling for key management operations. ```python try: key = Sm2Key() key.import_encrypted_private_key_info_pem('key.pem', 'wrong_password') except NativeError as e: print(f"Key import failed: {e}") ``` -------------------------------- ### Zuc Stream Cipher Encryption and Decryption Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Illustrates the encryption and decryption process using the Zuc stream cipher. This example shows how to initialize the Zuc cipher with a key and IV, then use the update and finish methods to process data. The interface is consistent with other block ciphers like Sm4Cbc. ```python from gmssl import * iv = rand_bytes(ZUC_IV_SIZE) plaintext = b'abc' zuc_enc = Zuc(key, iv) ciphertext = zuc_enc.update(plaintext) ciphertext += zuc_enc.finish() zuc_dec = Zuc(key, iv) decrypted = zuc_dec.update(ciphertext) decrypted += zuc_dec.finish() ``` -------------------------------- ### Sign and Verify with SM2 Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/README.md Illustrates how to generate an SM2 key pair, sign a message, and verify the signature. An identity string is required for signing and verification. ```python from gmssl import Sm2Key, Sm2Signature, DO_SIGN, DO_VERIFY key = Sm2Key() key.generate_key() signer = Sm2Signature(key, 'identity', DO_SIGN) signer.update(b'message') signature = signer.sign() verifier = Sm2Signature(key, 'identity', DO_VERIFY) verifier.update(b'message') is_valid = verifier.verify(signature) ``` -------------------------------- ### Create Empty Sm9EncMasterKey Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Initializes a new, empty Sm9EncMasterKey object. Subsequent operations require generating or importing a master key. ```python Sm9EncMasterKey() ``` -------------------------------- ### Initialize SM4-CTR Context Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Instantiate the Sm4Ctr class with a 16-byte key and a 16-byte IV. The IV must be unique for each encryption with the same key. ```python gmssl.Sm4Ctr(key: bytes, iv: bytes) ``` -------------------------------- ### SM9 Signature Initialization and Modes Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Initialize Sm9Signature for signing or verification. DO_SIGN is for signing, DO_VERIFY is for verification. ```python gmssl.Sm9Signature(sign: bool = DO_SIGN) ``` -------------------------------- ### Get SM9 User Key Identity Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Retrieves the identity associated with an SM9 signature user key as bytes. ```python Sm9SignKey.get_id() -> bytes ``` -------------------------------- ### Get User Identity from Sm9EncKey Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Retrieve the UTF-8 encoded user identity associated with the SM9 encryption key. ```python Sm9EncKey.get_id() -> bytes ``` -------------------------------- ### Sm4Cbc Constructor Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Initializes a new Sm4Cbc context for encryption or decryption. Requires a 16-byte key and a 16-byte initialization vector. ```APIDOC ## Sm4Cbc Constructor ### Description Initializes a new Sm4Cbc context for encryption or decryption. Requires a 16-byte key and a 16-byte initialization vector. ### Parameters #### Parameters - **key** (bytes) - Required - Encryption key; must be exactly 16 bytes - **iv** (bytes) - Required - Initialization vector; must be exactly 16 bytes - **encrypt** (bool) - Required - True for encryption, False for decryption ### Throws/Errors - Raises `ValueError` if key or IV length is incorrect - Raises `NativeError` on internal GmSSL error ``` -------------------------------- ### Instantiate Sm9EncKey Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Create an SM9 encryption key for a specific user. This key is typically obtained by extracting it from an SM9EncMasterKey. ```python gmssl.Sm9EncKey(owner_id: str) ``` -------------------------------- ### Get Certificate Validity Period Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/certificates.md Extracts the notBefore and notAfter dates from a certificate. Use this to check if a certificate is currently active. ```python from gmssl import Sm2Certificate import datetime cert = Sm2Certificate() cert.import_pem('mycert.pem') validity = cert.get_validity() now = datetime.datetime.now() if validity.not_before <= now <= validity.not_after: print("Certificate is currently valid") else: print("Certificate is expired or not yet valid") ``` -------------------------------- ### Initialize Sm3Hmac with a Key Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/hash.md Instantiate the Sm3Hmac class with a secret key. The key should be between 16 and 64 bytes for recommended security. This is used to initialize the HMAC computation. ```python from gmssl import Sm3Hmac, rand_bytes, SM3_HMAC_MIN_KEY_SIZE key = rand_bytes(SM3_HMAC_MIN_KEY_SIZE) hmac = Sm3Hmac(key) ``` -------------------------------- ### Upgrade GmSSL Library Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Follow these steps to upgrade an older GmSSL installation to a newer version. This involves pulling the latest code, recompiling, and reinstalling. ```bash cd GmSSL-master git pull origin master mkdir build && cd build cmake .. make sudo make install sudo ldconfig ``` -------------------------------- ### Instantiate Sm9EncMasterKey Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Creates an empty SM9 encryption master key instance. This key must be populated by calling `generate_master_key()` or importing a key before it can be used. ```python gmssl.Sm9EncMasterKey() ``` -------------------------------- ### Accessing gmssl-python Version Information Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/types.md Retrieve the version of the gmssl-python package and the linked libgmssl library. Ensure the gmssl library is installed and accessible to import these versions. ```python GMSSL_PYTHON_VERSION: str = "2.2.2" GMSSL_LIBRARY_VERSION: str = ``` ```python from gmssl import GMSSL_PYTHON_VERSION, GMSSL_LIBRARY_VERSION print(GMSSL_PYTHON_VERSION) # "2.2.2" print(GMSSL_LIBRARY_VERSION) # e.g., "3.1.1" ``` -------------------------------- ### Initialize Sm4Cbc Context Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Instantiate Sm4Cbc for encryption or decryption. Ensure the key and IV are exactly 16 bytes. Raises ValueError for incorrect key or IV lengths. ```python gmssl.Sm4Cbc(key: bytes, iv: bytes, encrypt: bool) ``` -------------------------------- ### Get Raw DER-Encoded Certificate Bytes Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/certificates.md Retrieves the complete certificate in its raw DER format as bytes. Useful for passing to other cryptographic libraries or for binary storage. ```python from gmssl import Sm2Certificate cert = Sm2Certificate() cert.import_pem('mycert.pem') raw_cert_bytes = cert.get_raw() # raw_cert_bytes is of type bytes ``` -------------------------------- ### Instantiate an Empty Sm2Certificate Object Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/certificates.md Creates an empty certificate object. You must call `import_pem()` to load certificate data before using other methods. ```python from gmssl import Sm2Certificate cert = Sm2Certificate() # cert.import_pem('mycert.pem') # Load certificate data here ``` -------------------------------- ### Update GmSSL Library Cache Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Run this command after installing or updating the GmSSL library to ensure the system can find it. It may be necessary to add the library path to LD_LIBRARY_PATH. ```bash sudo ldconfig export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH ``` -------------------------------- ### Sm3Hmac Constructor Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/hash.md Initializes a new Sm3Hmac instance with a secret key. The key should be between 16 and 64 bytes for recommended security. ```APIDOC ## Sm3Hmac(key: bytes) ### Description Initializes a new Sm3Hmac instance with the given secret key. This is used to compute an HMAC-SM3 message authentication code. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **key** (bytes) - Required - Secret key (16–64 bytes recommended) ### Request Example ```python from gmssl import Sm3Hmac, rand_bytes, SM3_HMAC_MIN_KEY_SIZE key = rand_bytes(SM3_HMAC_MIN_KEY_SIZE) hmac = Sm3Hmac(key) ``` ### Response #### Success Response (200) Returns a new Sm3Hmac instance. #### Response Example None ### Throws/Errors Raises `ValueError` if key length is not in range [SM3_HMAC_MIN_KEY_SIZE, SM3_HMAC_MAX_KEY_SIZE]. ``` -------------------------------- ### Handle StateError During Signing Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/types.md Example of catching StateError when attempting to sign using a Sm2Signature object initialized for verification. This illustrates how to manage state-related errors in signature operations. ```python try: verifier = Sm2Signature(key, 'ID', DO_VERIFY) signature = verifier.sign() # Wrong mode except StateError as e: print(f"Invalid operation: {e}") ``` -------------------------------- ### Complete SM9 Encryption Workflow Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Demonstrates the full SM9 encryption process, from master key generation by an authority to message encryption and decryption by users. Requires importing public master keys and user private keys. ```python from gmssl import Sm9EncMasterKey, rand_bytes # Authority: Generate master key master = Sm9EncMasterKey() master.generate_master_key() master.export_encrypted_master_key_info_pem('enc_msk.pem', 'authority_password') master.export_public_master_key_pem('enc_mpk.pem') # Authority: Generate key for Alice alice_key = master.extract_key('alice@example.com') alice_key.export_encrypted_private_key_info_pem('alice_enc_key.pem', 'alice_password') # Alice: Import her private key my_key = Sm9EncKey('alice@example.com') my_key.import_encrypted_private_key_info_pem('alice_enc_key.pem', 'alice_password') # Bob: Encrypt to Alice using public master key master_pub = Sm9EncMasterKey() master_pub.import_public_master_key_pem('enc_mpk.pem') message = b'Hello Alice' ciphertext = master_pub.encrypt(message, 'alice@example.com') # Alice: Decrypt the message plaintext = my_key.decrypt(ciphertext) ``` -------------------------------- ### Update Library Path on CentOS/RHEL Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Appends the GmSSL library path to the system's dynamic linker configuration and refreshes the cache. This is typically needed after installing the native library to /usr/local/lib. ```bash echo "/usr/local/lib" | sudo tee -a /etc/ld.so.conf sudo ldconfig ``` -------------------------------- ### Sm4 Constructor Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Initializes a new Sm4 cipher instance for encryption or decryption. The key must be exactly 16 bytes. ```APIDOC ## Sm4 Constructor ### Description Initializes a new Sm4 cipher instance for encryption or decryption. The key must be exactly 16 bytes. ### Method `Sm4(key: bytes, encrypt: bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **key** (bytes) - Required - Encryption key; must be exactly 16 bytes - **encrypt** (bool) - Required - True for encryption, False for decryption ### Throws/Errors - `ValueError`: If key length is not equal to SM4_KEY_SIZE (16 bytes). ### Example ```python from gmssl import Sm4, SM4_KEY_SIZE, rand_bytes, DO_ENCRYPT, DO_DECRYPT key = rand_bytes(SM4_KEY_SIZE) enc_cipher = Sm4(key, DO_ENCRYPT) dec_cipher = Sm4(key, DO_DECRYPT) ``` ``` -------------------------------- ### Sm9EncKey Constructor Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Initializes an SM9 encryption key for a specific user. The key is created with the user's identity and can later have its private decryption key imported or extracted. ```APIDOC ## Sm9EncKey(owner_id: str) ### Description Initializes an SM9 encryption key for a specific user. The key is created with the user's identity and can later have its private decryption key imported or extracted. ### Parameters #### Path Parameters - **owner_id** (str) - Required - User identity (email, domain, etc.) ### Return New Sm9EncKey instance (without private key material until imported or extracted). ``` -------------------------------- ### Get GmSSL Python and Library Version Information Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Retrieves the version of the gmssl-python wrapper and the underlying GmSSL C library. It also provides a numerical representation of the library version for comparisons. ```python import gmssl # Version of gmssl-python wrapper print(gmssl.GMSSL_PYTHON_VERSION) # "2.2.2" # Version of underlying GmSSL C library print(gmssl.GMSSL_LIBRARY_VERSION) # e.g., "3.1.1" # Library version as integer (for version comparison) ver_num = gmssl.gmssl_library_version_num() print(f"Library version number: {ver_num}") # e.g., 30101 ``` -------------------------------- ### Sm2Key.import_encrypted_private_key_info_pem() Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/asymmetric.md Imports a private key from a password-protected PEM file. ```APIDOC ## Method: Sm2Key.import_encrypted_private_key_info_pem() Import private key from password-protected PEM file. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | path | str | Yes | — | Path to encrypted PEM file | | passwd | str | Yes | — | Decryption password | **Return**: None. **Throws/Errors**: Raises `NativeError` on decryption failure or invalid password. **Example**: ```python from gmssl import Sm2Key imported_key = Sm2Key() imported_key.import_encrypted_private_key_info_pem('my_private_key.pem', 'MyPassword') ``` ``` -------------------------------- ### Catching StateError for API Misuse Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/errors.md Illustrates how to catch StateError, which is raised when a method is called in an incompatible operational state, indicating a programmer error. This example shows attempting to sign in a verification mode. ```python from gmssl import Sm2Key, Sm2Signature, DO_SIGN, DO_VERIFY, StateError try: key = Sm2Key() key.generate_key() verifier = Sm2Signature(key, 'ID', DO_VERIFY) verifier.update(b'message') sig = verifier.sign() # Wrong: in verify mode, not sign mode except StateError as e: print(f"API misuse: {e}") ``` -------------------------------- ### Finalize SM3 Hash and Get Digest Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/hash.md Finalizes the hash computation and returns the resulting 32-byte digest. After this call, the Sm3 object's state is finalized and must be reset to compute another hash. ```python from gmssl import Sm3 sm3 = Sm3() sm3.update(b'abc') dgst = sm3.digest() print(dgst.hex()) # 66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0 ``` -------------------------------- ### SM4 Block Cipher Encryption and Decryption Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Example of using the SM4 block cipher for encrypting and decrypting a single block of data. The SM4 class requires a key and a flag indicating encryption or decryption mode. ```python from gmssl import * key = rand_bytes(SM4_KEY_SIZE) plaintext = rand_bytes(SM4_BLOCK_SIZE) sm4_enc = Sm4(key, DO_ENCRYPT) ciphertext = sm4_enc.encrypt(plaintext) sm4_dec = Sm4(key, DO_DECRYPT) decrypted = sm4_dec.encrypt(ciphertext) ``` -------------------------------- ### Catching NativeError during Key Generation and Export Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/errors.md Demonstrates how to catch NativeError exceptions that may occur during cryptographic operations like key generation or exporting private keys. It suggests logging or notifying the user upon failure. ```python from gmssl import Sm2Key, NativeError try: key = Sm2Key() key.generate_key() key.export_encrypted_private_key_info_pem('key.pem', 'password') except NativeError as e: print(f"Cryptographic operation failed: {e}") # Handle error: log, notify user, retry, etc. ``` -------------------------------- ### Catching ValueError for Invalid Parameter Length Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/errors.md Shows how to catch ValueError, which occurs when input validation functions receive parameters with invalid types or ranges. This example demonstrates an attempt to create an Sm3Hmac with a key that is too short. ```python from gmssl import Sm3Hmac, rand_bytes, SM3_HMAC_MIN_KEY_SIZE try: short_key = rand_bytes(8) # Too short hmac = Sm3Hmac(short_key) except ValueError as e: print(f"Invalid parameter: {e}") ``` -------------------------------- ### Password-Based Key Derivation with sm3_pbkdf2 Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/hash.md This snippet demonstrates deriving a cryptographic key from a password using the PBKDF2 algorithm with SM3 as the underlying hash function. It includes generating a salt and storing it along with encrypted data for later decryption. The `SM3_PBKDF2_DEFAULT_SALT_SIZE` constant is used for salt generation. ```python from gmssl import sm3_pbkdf2, rand_bytes, SM3_PBKDF2_DEFAULT_SALT_SIZE password = "UserPassword" salt = rand_bytes(SM3_PBKDF2_DEFAULT_SALT_SIZE) key = sm3_pbkdf2(password, salt, 10000, 32) # Store salt + encrypted_data together; recompute key from password later import json stored = { 'salt': salt.hex(), 'encrypted_data': '...' } ``` -------------------------------- ### Import Encrypted Private Key into Sm9EncKey Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Import an encrypted private decryption key from a PEM file into the Sm9EncKey instance. Requires the file path and a password for decryption. ```python Sm9EncKey.import_encrypted_private_key_info_pem(path: str, passwd: str) -> None ``` -------------------------------- ### Import Public Master Key Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Imports the public master key from a PEM file. Used by regular users to encrypt to any recipient in the system. Requires the path to the public master key PEM file. Can throw NativeError on file read or parse failure. ```python from gmssl import Sm9EncMasterKey master_pub = Sm9EncMasterKey() master_pub.import_public_master_key_pem('enc_mpk.pem') ``` -------------------------------- ### Initialize SM4 Cipher Instance Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Instantiate the core SM4 block cipher for encryption or decryption. Ensure the key is exactly 16 bytes. This is typically a building block for higher-level modes. ```python from gmssl import Sm4, SM4_KEY_SIZE, rand_bytes, DO_ENCRYPT, DO_DECRYPT key = rand_bytes(SM4_KEY_SIZE) enc_cipher = Sm4(key, DO_ENCRYPT) dec_cipher = Sm4(key, DO_DECRYPT) ``` -------------------------------- ### Initialize SM3 Hash Object Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/hash.md Creates a new Sm3 instance ready for hashing. This object can be reused for multiple hash computations after resetting. ```python from gmssl import Sm3 sm3 = Sm3() ``` -------------------------------- ### Import Encrypted SM2 Private Key Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/asymmetric.md Imports a private key from a password-protected PEM file. Requires the correct password for decryption. ```python from gmssl import Sm2Key imported_key = Sm2Key() imported_key.import_encrypted_private_key_info_pem('my_private_key.pem', 'MyPassword') ``` -------------------------------- ### Sm4Gcm Constructor Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Initializes a new Sm4Gcm context for encryption or decryption. It requires a key, initialization vector (IV), and additional authenticated data (AAD). Optional parameters include tag length and the operation mode (encrypt/decrypt). ```APIDOC ## Sm4Gcm Constructor ### Description Initializes a new Sm4Gcm context for encryption or decryption. It requires a key, initialization vector (IV), and additional authenticated data (AAD). Optional parameters include tag length and the operation mode (encrypt/decrypt). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (bytes) - Required - Encryption key; must be exactly 16 bytes - **iv** (bytes) - Required - Initialization vector (1–64 bytes; 12 bytes recommended) - **aad** (bytes) - Required - Additional Authenticated Data (header to authenticate but not encrypt; can be empty) - **taglen** (int) - Optional - Default: SM4_GCM_DEFAULT_TAG_SIZE - Authentication tag length (1–16 bytes) - **encrypt** (bool) - Optional - Default: True - True for encryption, False for decryption ### Request Example ```python # Example for encryption gmssl.Sm4Gcm(key=b'...', iv=b'...', aad=b'...', taglen=16, encrypt=True) # Example for decryption gmssl.Sm4Gcm(key=b'...', iv=b'...', aad=b'...', taglen=16, encrypt=False) ``` ### Response #### Success Response (200) Returns a new Sm4Gcm context object. #### Response Example ```json { "message": "Sm4Gcm context created successfully" } ``` ### Errors - `ValueError`: If key length is incorrect. - `ValueError`: If IV length is outside the valid range [SM4_GCM_MIN_IV_SIZE, SM4_GCM_MAX_IV_SIZE]. - `ValueError`: If taglen is invalid. - `NativeError`: On GmSSL error. ``` -------------------------------- ### Secure File Encryption using SM4-GCM Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Demonstrates how to encrypt plaintext using the SM4-GCM algorithm. The resulting ciphertext includes the Initialization Vector (IV) and the authentication tag. ```python from gmssl import Sm4Gcm, rand_bytes, SM4_KEY_SIZE, SM4_GCM_DEFAULT_IV_SIZE import os plaintext = b'confidential content' key = rand_bytes(SM4_KEY_SIZE) iv = rand_bytes(SM4_GCM_DEFAULT_IV_SIZE) gcm = Sm4Gcm(key, iv, b'', taglen=16, encrypt=True) ciphertext = gcm.update(plaintext) + gcm.finish() # Store: iv || ciphertext (tag appended to ciphertext) file_data = iv + ciphertext ``` -------------------------------- ### Instantiate SM9 Signature Master Key Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Creates an empty SM9 signature master key instance. This is analogous to Sm9EncMasterKey but specifically for digital signatures and separate from the encryption master key. ```python gmssl.Sm9SignMasterKey() ``` -------------------------------- ### Import Public Symbols Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/INDEX.md Import all public symbols from the gmssl library. ```python # Import all public symbols from gmssl import * ``` -------------------------------- ### Import Encrypted SM9 User Private Key Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Imports an encrypted SM9 user private signing key from a specified PEM file path using a given password. ```python Sm9SignKey.import_encrypted_private_key_info_pem(path: str, passwd: str) -> None ``` -------------------------------- ### Sm2Key.import_public_key_info_pem Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/asymmetric.md Imports a public key from a PEM file. After import, only signature verification and encryption operations are available. ```APIDOC ## Sm2Key.import_public_key_info_pem ### Description Imports a public key from a PEM file. After import, only signature verification and encryption operations are available. ### Method `import_public_key_info_pem` ### Parameters #### Path Parameters - **path** (str) - Yes - Path to public key PEM file ### Request Example ```python from gmssl import Sm2Key pub_key = Sm2Key() pub_key.import_public_key_info_pem('their_public_key.pem') ``` ### Throws/Errors - Raises `NativeError` on parse failure. ``` -------------------------------- ### Define Sm2Certificate Wrapper Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/types.md Defines a wrapper class for an opaque SM2 X.509v3 certificate buffer. It is initialized via the constructor and populated using import_pem(). ```python class Sm2Certificate: _cert: c_void_p # Opaque certificate buffer ``` -------------------------------- ### Import and Parse a PEM-encoded SM2 Certificate Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Demonstrates how to import a PEM-encoded SM2 certificate using `Sm2Certificate.import_pem()` and then parse its content using the `gmssl certparse` command-line tool. This is useful for inspecting certificate details before programmatic use. ```text -----BEGIN CERTIFICATE----- MIIBszCCAVegAwIBAgIIaeL+wBcKxnswDAYIKoEcz1UBg3UFADAuMQswCQYDVQQG EwJDTjEOMAwGA1UECgwFTlJDQUMxDzANBgNVBAMMBlJPT1RDQTAeFw0xMjA3MTQw MDMxMTU5WkYwNDIyMDcwMzExNTlaMC4xCzAJBgNVBAYTAkNOMQ4wDAYDVQQKDAVO UkNBQzEPMA0GA1UEAwwGUk9PVENBMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE MPCca6pmgcchsTf2UnBeL9rtp4nw+itk1Kzrmbnqo05lUwkwlWK+4OIrtFdAqnRT V7Q9v1htkv42TsIutzd126NdMFswHwYDVR0jBBgwFoAUTDKxl9kzG8SmBcHG5Yti W/CXdlgwDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFEwysZfZ MxvEpgXBxuWLYlvwl3ZYMAwGCCqBHM9VAYN1BQADSAAwRQIgG1bSLeOXp3oB8H7b 53W+CKOPl2PknmWEq/lMhtn25HkCIQDaHDgWxWFtnCrBjH16/W3Ezn7U/Vjo5xI pDoiVhsLwg== -----END CERTIFICATE----- ``` ```bash $gmssl certparse -in ROOTCA.pemCertificate ``` -------------------------------- ### Sm2Signature Constructor Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/asymmetric.md Initializes a new Sm2Signature instance for signing or verification. The behavior and usability of methods depend on the 'sign' parameter. ```APIDOC ## Sm2Signature Constructor ### Description Initializes a new Sm2Signature instance for signing or verification. The behavior and usability of methods depend on the 'sign' parameter. ### Method Signature ```python Sm2Signature(sm2_key: Sm2Key, signer_id: str = SM2_DEFAULT_ID, sign: bool = DO_SIGN) ``` ### Parameters #### Parameters - **sm2_key** (Sm2Key) - Required - Key to sign or verify with - **signer_id** (str) - Optional - Identity string for signature (16 bytes UTF-8). Defaults to SM2_DEFAULT_ID. - **sign** (bool) - Optional - True for signing, False for verification. Defaults to DO_SIGN. ### Return New Sm2Signature instance. ### Behavior - If `sign=DO_SIGN`, key must have private key; only `sign()` method is usable. - If `sign=DO_VERIFY`, key can be public-only; only `verify()` method is usable. - `signer_id` is bound at construction and used in signature computation. ### Throws/Errors Raises `NativeError` if key state doesn't match the requested mode. ### Example ```python from gmssl import Sm2Key, Sm2Signature, DO_SIGN, DO_VERIFY # Signing side key = Sm2Key() key.generate_key() signer = Sm2Signature(key, 'Alice', DO_SIGN) signer.update(b'message') signature = signer.sign() # Verification side pub_key = Sm2Key() pub_key.import_public_key_info_pem('alice_pub.pem') verifier = Sm2Signature(pub_key, 'Alice', DO_VERIFY) verifier.update(b'message') is_valid = verifier.verify(signature) ``` ``` -------------------------------- ### Import Public Key from PEM Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/asymmetric.md Imports a public key from a PEM file. After import, only signature verification and encryption operations are available. Ensure the provided path points to a valid public key PEM file. ```python from gmssl import Sm2Key pub_key = Sm2Key() pub_key.import_public_key_info_pem('their_public_key.pem') ``` -------------------------------- ### Import Encrypted Master Key Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Imports the encrypted master key from a PEM file (private component). Requires the path to the encrypted PEM master key file and the decryption password. Can throw NativeError on decryption failure or invalid password. ```python from gmssl import Sm9EncMasterKey master = Sm9EncMasterKey() master.import_encrypted_master_key_info_pem('enc_msk.pem', 'password') ``` -------------------------------- ### Verify SM3 Hash with Command Line Source: https://github.com/gmssl/gmssl-python/blob/main/README.md Compares the SM3 hash computed by the Python script with the output from the gmssl command-line tool. ```bash echo -n abc | gmssl sm3 ``` -------------------------------- ### Initialize and Use ZUC Stream Cipher Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Demonstrates encrypting and then decrypting data using the ZUC stream cipher. Ensure a unique (key, IV) pair for each encryption session. The output length of encrypted data is approximately the same as the input plaintext length. ```python from gmssl import Zuc, ZUC_KEY_SIZE, ZUC_IV_SIZE, rand_bytes key = rand_bytes(ZUC_KEY_SIZE) iv = rand_bytes(ZUC_IV_SIZE) plaintext = b'message' # Encrypt zuc_enc = Zuc(key, iv) ciphertext = zuc_enc.update(plaintext) ciphertext += zuc_enc.finish() # Decrypt (same key-IV pair, same operation) zuc_dec = Zuc(key, iv) decrypted = zuc_dec.update(ciphertext) decrypted += zuc_dec.finish() assert decrypted == plaintext assert len(ciphertext) == len(plaintext) ``` -------------------------------- ### Sm9Signature Constructor Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Initializes a new Sm9Signature instance for either signing or verification. The mode is determined by the 'sign' parameter. ```APIDOC ## Sm9Signature Constructor ### Description Initializes a new Sm9Signature instance for either signing or verification. The mode is determined by the 'sign' parameter. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **sign** (bool) - Optional - Default: DO_SIGN - True for signing, False for verification ### Request Example ```python from gmssl import Sm9Signature, DO_SIGN, DO_VERIFY signer = Sm9Signature(DO_SIGN) # For signing verifier = Sm9Signature(DO_VERIFY) # For verification ``` ### Response #### Success Response (200) Returns a new Sm9Signature instance. #### Response Example None ``` -------------------------------- ### Encrypt and Decrypt with SM4 CBC Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/README.md Shows how to perform SM4 encryption and decryption using CBC mode. Requires random key and IV generation. ```python from gmssl import Sm4Cbc, SM4_KEY_SIZE, SM4_CBC_IV_SIZE, rand_bytes, DO_ENCRYPT, DO_DECRYPT key = rand_bytes(SM4_KEY_SIZE) iv = rand_bytes(SM4_CBC_IV_SIZE) enc = Sm4Cbc(key, iv, DO_ENCRYPT) ciphertext = enc.update(b'plaintext') + enc.finish() dec = Sm4Cbc(key, iv, DO_DECRYPT) plaintext = dec.update(ciphertext) + dec.finish() ``` -------------------------------- ### Import Encrypted SM9 Signature Master Key Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Imports an encrypted SM9 signature master key from a specified PEM file path using a given password. ```python Sm9SignMasterKey.import_encrypted_master_key_info_pem(path: str, passwd: str) -> None ``` -------------------------------- ### Safe Threading Pattern with Sm3 Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/INDEX.md Demonstrates the recommended practice of using a separate Sm3 object for each thread to maintain state integrity. This avoids potential corruption when accessing cryptographic objects concurrently. ```python import threading # Thread 1 sm3_1 = Sm3() sm3_1.update(b'data1') # Thread 2 sm3_2 = Sm3() # Different object sm3_2.update(b'data2') ``` -------------------------------- ### Check Certificate File Existence Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/configuration.md Verify if a certificate file exists before attempting to import it. This Python snippet checks for the file's presence and prints a message if it's not found. ```python import os cert_path = 'cert.pem' if not os.path.exists(cert_path): print(f"Certificate not found: {cert_path}") else: cert = Sm2Certificate() cert.import_pem(cert_path) ``` -------------------------------- ### Sm9EncKey.import_encrypted_private_key_info_pem Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/sm9.md Imports an encrypted private decryption key from a PEM file into the Sm9EncKey instance. Requires the file path and the decryption password. ```APIDOC ## Sm9EncKey.import_encrypted_private_key_info_pem(path: str, passwd: str) ### Description Imports an encrypted private decryption key from a PEM file into the Sm9EncKey instance. Requires the file path and the decryption password. ### Parameters #### Path Parameters - **path** (str) - Required - Path to encrypted key PEM file - **passwd** (str) - Required - Decryption password ### Return None. ### Throws/Errors Raises `NativeError` on decryption or parse failure. ``` -------------------------------- ### Sm4Ctr Constructor Source: https://github.com/gmssl/gmssl-python/blob/main/_autodocs/api-reference/symmetric.md Initializes the SM4-CTR cipher context. This constructor is used for both encryption and decryption in CTR mode. It requires a 16-byte key and a unique 16-byte IV (nonce/counter) for each encryption/decryption operation. ```APIDOC ## Sm4Ctr(key: bytes, iv: bytes) ### Description Initializes a new SM4-CTR context for symmetric encryption and decryption using the SM4 cipher in Counter Mode. This mode processes arbitrary-length messages without padding, and the output is the same length as the input. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **key** (bytes) - Required - The encryption key. Must be exactly 16 bytes. * **iv** (bytes) - Required - The nonce/counter Initialization Vector (IV). Must be exactly 16 bytes and unique per key for each operation. ### Throws/Errors * `ValueError`: Raised if the key or IV length is incorrect. * `NativeError`: Raised on internal errors during initialization. ```