National Cryptographic Algorithms (SM series) are China's independently developed cryptographic standards, formulated and published by the State Cryptographic Administration. With the changing cybersecurity landscape and the requirement for independent and controllable domestic cryptography, the application of SM algorithms in domestic information systems is becoming increasingly widespread. This article introduces three core SM algorithms: SM2 (asymmetric encryption), SM3 (hash algorithm), and SM4 (symmetric encryption).
I. Overview of SM Algorithms
The SM algorithm system mainly includes the following core algorithms:
| Algorithm | Type | Usage | Corresponding International Standard |
|---|---|---|---|
| SM2 | Asymmetric Encryption/Signature | Key Exchange, Digital Signature | RSA/ECC |
| SM3 | Hash Algorithm | Data Integrity Verification | SHA-256 |
| SM4 | Symmetric Encryption | Data Encryption Transmission | AES |
| SM9 | Identity-Based Cryptography | Identity-Based Encryption | None |
II. SM2 Elliptic Curve Public Key Cryptographic Algorithm
SM2 is an asymmetric cryptographic algorithm based on elliptic curves, mainly used for digital signature, key exchange, and public key encryption. It is China's independently designed elliptic curve cryptographic algorithm with higher security than RSA.
Algorithm Principles
SM2 is based on the Elliptic Curve Discrete Logarithm Problem (ECDLP), whose core is to perform operations on elliptic curves over finite fields. The mathematical foundation of elliptic curve cryptography is: on an elliptic curve, given two points P and Q = kP (where k is the private key), calculating k from P and Q is a hard problem, which is the Elliptic Curve Discrete Logarithm Problem. The elliptic curve parameters used by SM2 are specified by the State Cryptographic Administration, using a Weierstrass curve over a prime field, ensuring the security and compliance of the algorithm.
The security of SM2 relies on the computational difficulty of the Elliptic Curve Discrete Logarithm Problem. Computationally, given two points P and Q on an elliptic curve, finding an integer k such that Q = kP is a recognized hard problem, and there is currently no efficient polynomial-time algorithm to solve this problem.
Basic Process
- Key Generation: Generate a pair of public and private keys, the public key is public, and the private key is kept secret
- Signature: Use the private key to sign the message
- Verification: Use the public key to verify the validity of the signature
- Encryption: Use the public key to encrypt data
- Decryption: Use the private key to decrypt data
Frontend Implementation Example
// SM2 key pair generation
async function generateSM2KeyPair() {
// Use Web Crypto API or third-party library
const keyPair = await window.crypto.subtle.generateKey(
{
name: 'ECDSA',
namedCurve: 'SM2' // supported in some browsers
},
true,
['sign', 'verify']
);
return {
publicKey: await window.crypto.subtle.exportKey('spki', keyPair.publicKey),
privateKey: await window.crypto.subtle.exportKey('pkcs8', keyPair.privateKey)
};
}
// SM2 sign
async function sm2Sign(privateKey, message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const signature = await window.crypto.subtle.sign(
{
name: 'ECDSA',
hash: 'SM3'
},
privateKey,
data
);
return signature;
}
// SM2 verify
async function sm2Verify(publicKey, message, signature) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const isValid = await window.crypto.subtle.verify(
{
name: 'ECDSA',
hash: 'SM3'
},
publicKey,
signature,
data
);
return isValid;
}
π‘ Tip:Current mainstream browsers have limited native support for SM2. It is recommended to use third-party libraries such as sm-crypto or gm-crypto to implement SM algorithms on the frontend.
III. SM3 Cryptographic Hash Algorithm
SM3 is a cryptographic hash algorithm used to generate fixed-length digests of messages, which can be used for data integrity verification and digital signatures. The security of SM3 is comparable to SHA-256.
Algorithm Features
SM3 has the following core features: 1) One-way: it is impossible to restore the original message from a hash value; 2) Collision resistance: it is difficult to find two different messages that produce the same hash value; 3) Avalanche effect: a small change in the message will cause a huge change in the hash value; 4) Fixed output: no matter how long the input message is, the output is always 256 bits (32 bytes).
- Output length: 256 bits (32 bytes)
- Message block: 512 bits
- Iterative compression: 64 rounds
- Collision resistance: strong collision resistance
Algorithm Flow
The processing of SM3 is divided into three stages: message padding, message expansion, and compression function. The message is first padded to a multiple of 512 bits, then expanded to generate 68 32-bit words through message expansion, and finally processed iteratively through 64 rounds of compression function, ultimately generating a 256-bit hash value.
- Message Padding: Pad the message to a multiple of 512 bits
- Message Expansion: Expand each 512-bit block into 132 words
- Iterative Compression: Perform 64 rounds of compression operations on each block
- Output Digest: Output the 256-bit hash value
Frontend Implementation Example
// Calculate SM3 using sm-crypto library
import { sm3 } from 'sm-crypto';
// Calculate SM3 hash of string
const message = 'Hello, SM3!';
const hash = sm3(message);
console.log('SM3 Hash:', hash);
// Calculate SM3 hash of byte array
const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
const hashBytes = sm3(bytes);
console.log('SM3 Hash (bytes):', hashBytes);
// Verify data integrity
function verifyData(original, hash) {
const newHash = sm3(original);
return newHash === hash;
}
IV. SM4 Block Cipher Algorithm
SM4 is a block symmetric cryptographic algorithm used for data encryption and decryption. It adopts 128-bit blocks and 128-bit keys, supporting multiple working modes.
Algorithm Features
SM4 has the following core features: 1) Both block length and key length are 128 bits; 2) Adopts a non-Feistel structure round function design; 3) Uses S-boxes and linear transformations to achieve confusion and diffusion; 4) Encryption and decryption use the same structure, only the order of round keys is reversed; 5) Supports multiple working modes such as ECB, CBC, CTR, GCM, etc.
- Block length: 128 bits
- Key length: 128 bits
- Number of rounds: 32 rounds
- Working modes: ECB, CBC, CFB, OFB, CTR, etc.
Algorithm Flow
The encryption and decryption processes of SM4 are exactly the same, only the order of round key usage is reversed. The algorithm performs 32 rounds of iteration, each round using a round key and a nonlinear transformation. The round keys are generated from the original key through a key expansion algorithm, generating a total of 32 round keys.
- Key Expansion: Expand the 128-bit key into 32 round keys
- Initial Transformation: Perform initial transformation on the plaintext
- Round Function Transformation: Perform 32 rounds of iterative transformation
- Inverse Initial Transformation: Perform inverse initial transformation to obtain ciphertext
Frontend Implementation Example
// SM4 encryption/decryption using sm-crypto library
import { sm4 } from 'sm-crypto';
// SM4 encryption (ECB mode)
const key = '0123456789abcdeffedcba9876543210'; // 16-byte key
const plaintext = 'Hello, SM4!';
// ECB mode encryption
const ciphertext = sm4.encrypt(plaintext, key);
console.log('SM4 ECB Ciphertext:', ciphertext);
// ECB mode decryption
const decrypted = sm4.decrypt(ciphertext, key);
console.log('SM4 ECB Decrypted:', decrypted);
// CBC mode encryption
const iv = '00000000000000000000000000000000'; // 16-byte initialization vector
const ciphertextCbc = sm4.encrypt(plaintext, key, { mode: 'cbc', iv });
console.log('SM4 CBC Ciphertext:', ciphertextCbc);
// CBC mode decryption
const decryptedCbc = sm4.decrypt(ciphertextCbc, key, { mode: 'cbc', iv });
console.log('SM4 CBC Decrypted:', decryptedCbc);
V. Application Scenarios of SM Algorithms
1. Digital Signature
Use SM2 for digital signature and SM3 for hash calculation to ensure document authenticity and integrity:
Typical applications include: electronic contract signing, electronic invoice verification, government document approval, financial transaction confirmation, etc. In these scenarios, digital signatures not only ensure data integrity but also provide identity authentication and responsibility identification functions.
const message = 'Important contract document content';
// Step 1: Calculate SM3 hash of message
const hash = sm3(message);
// Step 2: Sign hash with SM2 private key
const signature = sm2.sign(privateKey, hash);
// Step 3: Verify signature
const isValid = sm2.verify(publicKey, hash, signature);
2. Data Encryption Transmission
Use SM4 to encrypt data and SM2 to exchange keys:
Typical applications include: VPN encryption tunnels, HTTPS encrypted communication, database encrypted storage, cloud service data transmission, etc. The high efficiency of SM4 makes it particularly suitable for large data volume encryption scenarios, while the asymmetric nature of SM2 solves the key distribution problem.
// Generate random SM4 key
const sm4Key = crypto.randomBytes(16).toString('hex');
// Encrypt SM4 key with SM2 public key
const encryptedKey = sm2.encrypt(publicKey, sm4Key);
// Encrypt actual data with SM4
const ciphertext = sm4.encrypt(data, sm4Key);
// Transmit encryptedKey + ciphertext
// Receiver decrypts SM4 key with SM2 private key, then decrypts data
3. Identity Authentication
Use SM2 signature for identity authentication:
Typical applications include: digital certificate authentication, single sign-on systems, IoT device authentication, blockchain identity verification, etc. Identity authentication systems implemented through SM algorithms not only meet security requirements but also comply with domestic compliance standards.
// Server generates random challenge during user login
const challenge = crypto.randomBytes(32).toString('hex');
// User signs challenge with SM2 private key
const signature = sm2.sign(userPrivateKey, challenge);
// Server verifies signature with user's public key
const isValid = sm2.verify(userPublicKey, challenge, signature);
VI. Comparison of SM Algorithms and International Algorithms
| Feature | SM Algorithms | International Algorithms |
|---|---|---|
| Asymmetric Encryption | SM2 (256-bit curve) | RSA (2048+ bits)/ECC (256 bits) |
| Hash Algorithm | SM3 (256 bits) | SHA-256 (256 bits) |
| Symmetric Encryption | SM4 (128 bits) | AES (128/256 bits) |
| Security | High, independently controllable | High, but relies on foreign standards |
| Compliance Requirements | Mandatory in China | Internationally accepted |
VII. Practical Suggestions
1. Choose the Right Library
- sm-crypto: Lightweight SM algorithm library, supporting SM2/SM3/SM4
- gm-crypto: SM algorithm implementation based on OpenSSL
- webcrypto-core: Extends Web Crypto API to support SM algorithms
2. Key Management
- Private keys must be properly stored to avoid leakage
- Use secure key storage solutions (such as Web Crypto API's keyUsage)
- Regularly rotate keys
3. Mode Selection
- For symmetric encryption, prefer CBC or CTR mode, avoid ECB
- Use a random initialization vector (IV) for each encryption
- Ensure the randomness and uniqueness of IV
4. Compliance Requirements
In domestic systems involving sensitive data, SM algorithms should be prioritized to meet the compliance requirements of information security level protection.
VIII. Summary
SM algorithms are important achievements in China's cryptography field, including three core algorithms SM2, SM3, and SM4, corresponding to asymmetric encryption, hash, and symmetric encryption respectively. With the increasing requirement for independent and controllable domestic cryptography, mastering the principles and applications of SM algorithms is becoming more and more important for developers.
In actual development, the appropriate algorithm combination should be selected according to specific scenarios, and mature third-party libraries should be used to ensure the correctness and security of the implementation.