Home / Developer Tool Guides / SM4 Guide

The Complete SM4 Block Cipher Guide

From historical background to real-world application: a comprehensive guide to SM4's core principles, 32-round iteration structure, ECB/CBC and other modes, key and IV management, 7 real-world use cases, AES-128 comparison, practical tips and data security recommendations.

📖 About 10 min read 📅 Updated Jun 20, 2026 ✍️ Tudousi Tools Team
🔐 Try the SM4 Encryption/Decryption Tool Now
Encrypt and decrypt with SM4 online. Supports ECB/CBC modes, Hex/Base64 encoding, result copy and download. All operations run locally in your browser to protect your privacy.
Open Tool
#01

What Is SM4? Understanding Its Nature and Historical Place

SM4 (commercial block cipher) was published by China's State Cryptography Administration in 2012 (GM/T 0007-2012) as the official symmetric encryption standard of the Guomi cryptography family. It operates on 128-bit blocks using a 128-bit key through 32 rounds of nonlinear iteration, with the same algorithm structure used for both encryption and decryption (equivalent decryption), differing only in the round key order.

As the official symmetric encryption standard of the Guomi system, SM4's publication marked China's achievement of a self-controlled national standard in symmetric cryptography. Its design draws on the general ideas of AES (SP network structure, block cipher, multiple rounds of iteration), but uses entirely different S-box, linear transformation, and round function designs to achieve a comparable level of security.

After more than a decade of public application and academic scrutiny, SM4 is currently considered secure: no practical attack method has been publicly disclosed. It is widely used in WAPI security protocols, wireless LAN authentication, e-government, financial IC cards, database field encryption, disk and file encryption, and real-time data transmission protection. SM4 is the preferred Guomi symmetric encryption algorithm to meet "Level 2 Protection" and financial-level compliance requirements.

Our online SM4 tool preserves the practical value of the algorithm while providing developers with one-click online encryption/decryption and result copying.

#02

How SM4 Works: 32-Round Iteration, S-box, and Linear Transformation

SM4's core operation can be summarized in one sentence: a 128-bit plaintext block is processed through 32 rounds of nonlinear transformation, ultimately producing a 128-bit ciphertext block. Understanding this is essential for using SM4 correctly.

The specific steps are:

  • Input processing: The 128-bit plaintext is split into 4 32-bit words: X0, X1, X2, X3.
  • Round function: Each round computes X[i+4] = X[i] ⊕ T(X[i+1] ⊕ X[i+2] ⊕ X[i+3] ⊕ rk[i]), where T is a composite transformation (nonlinear S-box + linear transformation L), and rk[i] is the round key.
  • Nonlinear S-box: An 8-bit input is replaced by a fixed lookup table with another 8-bit output, providing confusion capability. SM4's S-box is constructed over the finite field GF(2^8) with good differential uniformity and nonlinearity.
  • Linear transformation L: The S-box output undergoes a 32-bit linear transformation (cyclic shift + XOR), providing diffusion capability to ensure that a change in a single plaintext bit affects many ciphertext bits.
  • Key expansion: A 128-bit master key is expanded into 32 32-bit round keys rk[0..31] using a composite transformation T' together with fixed system parameters FK and CK.
  • Iterative computation: A total of 32 rounds of the round function are executed, each using one round key.
  • Reverse-order output: The last 4 state words are concatenated in reverse order to produce the 128-bit ciphertext: Y = (X35, X34, X33, X32).
  • Decryption: Uses the same algorithm structure — simply reverse the order of the round keys (from rk[31] to rk[0]) to decrypt, which is what "equivalent decryption" means.

Once you understand this structure, you can accurately answer why the key length is fixed at 128 bits, why each block is encrypted independently in ECB mode, and why the IV is so important in CBC mode.

#03

Block Cipher Modes & Padding: ECB, CBC, PKCS7 in Practice

SM4 by itself only defines how to encrypt/decrypt a single 128-bit block. To encrypt longer data, a block cipher mode of operation is required. Different modes trade off security, implementation complexity, and parallelism.

ECB (Electronic Codebook)

  • Each 128-bit block is encrypted independently with the same key.
  • Pros: simple implementation, encryption can be parallelized.
  • Cons: Identical plaintext blocks → identical ciphertext blocks, so plaintext patterns are not hidden. An attacker can substitute or reorder blocks to mount attacks.
  • Not recommended for sensitive data encryption. Only acceptable when data blocks are naturally independent and pattern leakage is not an issue.

CBC (Cipher Block Chaining)

  • Before encryption, each plaintext block is XORed with the previous ciphertext block. The first block is XORed with an Initialization Vector (IV).
  • Pros: plaintext patterns are hidden (identical plaintext yields different ciphertext), security is significantly higher than ECB.
  • Cons: encryption cannot be parallelized (decryption can be partially parallelized in some implementations); a single-bit error in a ciphertext block corrupts that entire block and the corresponding bit in the next block.
  • The most widely used and recommended mode today.

PKCS7 Padding

  • When the plaintext length is not an integer multiple of 128 bits (16 bytes), padding is applied to complete the block before encryption.
  • PKCS7: if N bytes are missing → fill with N bytes, each byte value being N. For example, if 3 bytes are missing, the padding is 0x03 0x03 0x03.
  • If the plaintext length is exactly a multiple of 16 bytes, an additional 16 bytes of padding (each with value 16) are appended, to ensure the decryption side can reliably remove padding.
  • NOPADDING (no padding): input must be exactly a multiple of 16 bytes, otherwise the operation will fail. Useful for pre-aligned data.

Regarding encoding formats: Hex (hexadecimal) is convenient for human reading and debugging; Base64 is more compact, suitable for transmission in email, URL parameters, and similar scenarios.

#04

7 Real-World Use Cases: When Do You Need SM4?

As the Guomi standard symmetric encryption algorithm, SM4's application scenarios revolve around three keywords: "compliance required + symmetric encryption needed + high performance required".

① WAPI and Wireless LAN Authentication

In China's indigenous WLAN Authentication and Privacy Infrastructure (WAPI), SM4 is the core symmetric encryption algorithm used for session confidentiality between wireless terminals and access points.

② Financial IC Cards & POS Terminals

In financial IC cards and mobile payment terminals, SM4 is used for transaction message encryption, PIN protection, and sensitive field encryption/decryption, satisfying the Guomi requirements of the China Financial Integrated Circuit (IC) Card Specification.

③ Database Field Encryption

Sensitive fields such as ID numbers, mobile phone numbers, and bank card numbers are encrypted with SM4 before being written to the database. Even if the database is breached, the attacker cannot directly read sensitive information. Combined with a Key Management System (KMS), more complete data masking can be achieved.

④ E-government & Confidential Document Transmission

In government systems, sensitive documents and data transmission channels are often required to use Guomi algorithms. SM4 is used for symmetric encryption of transmitted content, usually combined with SM2 (asymmetric) and SM3 (hash) to form a complete Guomi cipher stack.

⑤ Disk & File Encryption

Scenarios requiring encryption protection for disk partitions or individual files (such as enterprise endpoint management, Data Leak Prevention DLP). SM4 provides high-performance symmetric encryption capability with both compliance and security.

⑥ Real-Time Data Transmission Protection (VPN / TLS Replacement)

In Guomi-certified VPN and SSL/TLS gateways, SM4 serves as the session encryption algorithm after handshake for large-batch symmetric data encryption. Performance is close to AES-128, and it is widely deployed in domestic cybersecurity products.

⑦ IoT Device Data Encryption

Resource-constrained IoT devices (smart water meters, smart door locks, industrial sensors) need lightweight encryption. SM4's S-box design is very efficient for hardware implementation, making it suitable for ASIC/FPGA or low-power MCU scenarios.

In short: Whenever you need symmetric encryption, and your scenario involves Chinese national standards, government, finance, or Level 2 Protection requirements, SM4 is your first choice for compliance and security.

#05

SM4 vs AES-128: Choosing the Right Symmetric Algorithm

SM4 and AES-128 are currently the two most mainstream 128-bit block symmetric encryption algorithms. They each have different characteristics in security strength, performance, and ecosystem support.

Security Strength Comparison

  • SM4: 128-bit key, 128-bit block, 32 rounds. No practical attack methods publicly disclosed at present.
  • AES-128: 128-bit key, 128-bit block, 10 rounds. Survived more than 20 years of global cryptanalysis.
  • Conclusion: Both are considered to have roughly equivalent security strength.

Performance Comparison

  • Software implementation: AES has hardware instruction sets (AES-NI) on most modern CPUs, giving higher throughput per round. SM4 does not have dedicated instruction-set support.
  • Hardware implementation: SM4's S-box structure is very ASIC/FPGA friendly, giving excellent performance on domestic chips and Guomi accelerator cards.
  • Conclusion: AES is faster on mainstream x86/ARM CPUs; SM4 has the advantage on Guomi-dedicated hardware.

Ecosystem & Compatibility Comparison

  • AES: universally used worldwide, natively supported by nearly all operating systems, browsers, TLS libraries, JDK, OpenSSL, etc.
  • SM4: primarily required within China. The GM/T specification series has been published for many years and is supported by libraries such as GmSSL and Bouncy Castle. International ecosystem support is being built up.
  • Conclusion: AES has a more mature ecosystem; SM4 is mandatory in domestic compliance scenarios.

Practical Selection Recommendations

  • Scenarios involving Chinese government, finance, Level 2 Protection, or Guomi migration → choose SM4.
  • Scenarios primarily targeting international markets, cross-platform compatibility, or integration with international standards → choose AES.
  • When in doubt, support both algorithms (dual-algorithm support is common in domestic products).
  • Regardless of which algorithm you choose, always pair it with a proper mode (CBC recommended), a reasonable IV strategy, and secure key management. The algorithm itself is secure, but incorrect usage can make the system insecure.
#06

5 Practical Tips: Avoid Common Pitfalls and Improve Reliability

① Prefer CBC Mode Over ECB

ECB mode yields identical ciphertext for identical plaintext, vulnerable to pattern analysis attacks. CBC mode hides plaintext patterns with significantly higher security strength. Unless you explicitly know ECB is safe in your scenario (extremely rare), you should default to CBC.

② Use a Different IV Every Encryption (and Make It Unpredictable)

In CBC mode, the IV does not need to be secret, but it must be unique and unpredictable. If two different messages use the same IV, an attacker can derive the XOR of their plaintexts. Always use a cryptographically secure random number generator to generate IVs (16 bytes).

③ Key Length Must Be Exactly 128 bits (16 Bytes)

SM4 uses a fixed 128-bit key. Never use a user-supplied password directly as a key ("password123" has far insufficient entropy). Use a cryptographically secure pseudo-random number generator (CSPRNG) to generate keys, or derive them from passwords via a KDF such as PBKDF2 or HKDF.

④ Never Hardcode Keys in Code or Config Files

Hardcoded keys, once decompiled or leaked through source code, compromise the entire system. The correct approach is to use a Key Management System (KMS), Hardware Security Module (HSM), or environment variables (only as a temporary measure in development environments).

⑤ Use Encryption + Integrity Check, Not Just Encryption

Encryption alone does not prevent ciphertext tampering. If you need data integrity and authenticity, append a message authentication code (such as HMAC-SM3) after encryption, or use an AEAD mode (like GCM, if supported by your library) that provides confidentiality and integrity simultaneously.

#07

Data Security & Privacy: Why Choose a Locally-Processing Online Tool

The first principle of using an online encryption tool is: keys and plaintext should never leave your device. All SM4 operations performed by this tool run locally in your browser through JavaScript; keys, plaintext, and ciphertext are never uploaded to any server.

Why is local processing so important?

  • The key is the root of trust in any encryption system. Once a key is leaked, no algorithm strength can save the system.
  • Prevent man-in-the-middle attacks: if data is transmitted over the network, it is at risk of sniffing or being replaced by an attacker.
  • Follows the principle of minimum disclosure: only data that must be transmitted should be transmitted. Encryption tool input and output are the most sensitive kinds of data.
  • No server log risk: cloud-based tools may log your request parameters, IP address, and access time.

Although this tool runs locally, you should still be aware of the following risks:

  • Do not process sensitive data on public computers — browser history, clipboard, and auto-save features may leak information.
  • Do not share keys via email or instant messaging over unencrypted channels.
  • Prefer strong random keys over human-memorable passwords.
  • Use a different IV for every CBC-mode encryption; never reuse.
  • For highly sensitive scenarios, you can load this page offline and then perform your operations (once downloaded, this page works completely without Internet).

All in all, SM4's value lies in its compliance status as a Guomi standard combined with AES-128-class security and good ecosystem compatibility. As long as you choose a privacy-conscious local tool, it remains a trustworthy option in a developer's toolbox.

Try Tudousi SM4 Online Tool Now →