DEV Community

HarmonyOS
HarmonyOS

Posted on

SM4 CTR Mode Encryption Decryption Fails When Using IVParams Spec

Read the original article:SM4 CTR Mode Encryption Decryption Fails When Using IVParams Spec

Problem Description

When using the SM4 encryption algorithm with CTR block mode, encryption and decryption fail after applying the IVParamsSpec parameter.
Error output:

decrypt ok enData: VLhJHQ==
decrypt ok deDate: ��G
decrypt failed
Enter fullscreen mode Exit fullscreen mode

Background Knowledge

  • The algorithm library currently supports 7 common SM4 encryption mode*s*: ECB, CBC, CTR, OFB, CFB, CFB128, GCM.
  • Each mode requires different parameters. Refer to ParamsSpec for detailed requirements.
  • IVParamsSpec specifies the initialization vector (IV), which acts as the data offset in block modes.
  • For SM4, the block size is 128 bits (16 bytes). Therefore, IV length must match the block size.

Troubleshooting Process

1.Reviewed code for both encryptMessagePromise and decryptMessagePromise.

2.Verified cipher creation:

 cryptoFramework.createCipher('SM4_128|CTR|NoPadding');
Enter fullscreen mode Exit fullscreen mode

Correct for CTR mode.

3.Checked IVParamsSpec:

   let smIV = '12345678' // 8 bytes only
Enter fullscreen mode Exit fullscreen mode

Confirmed that only 8 bytes were passed as IV.

4.Compared against SM4 requirements: CTR mode requires 16-byte IV.

5.Root cause: Invalid IV length caused mismatched offsets, leading to decryption errors.

Analysis Conclusion

  • The IV passed via IVParamsSpec was 8 bytes.
  • CTR mode in SM4 requires 16-byte IV.
  • Incorrect IV length directly caused encryption and decryption mismatch.

Solution

  • Update IV to 16 bytes when using CTR mode.

  • Example fix:

  let smIV = '1234567890abcdef'; // 16-byte IV
  let ivParamsSpec: cryptoFramework.IvParamsSpec = {
    algName: "IvParamsSpec",
    iv: { data: new Uint8Array(buffer.from(smIV, 'utf-8').buffer) }
  };
Enter fullscreen mode Exit fullscreen mode
  • Ensure both encryption and decryption use the same IV.

Verification Result

  • After updating IV to 16 bytes:
    • Encryption succeeded.
    • Decryption returned the correct original plaintext.
  • Tests confirmed consistent and repeatable results for both static and randomly generated 16-byte IVs.

Written by Arif Emre Ankara

Top comments (0)