SM4 Encryption-Decryption CTR Block Mode Fails with IVParamsSpec Parameter.
Problem Description
An error occurs when using the SM4 encryption/decryption algorithm with the CTR block mode after adding the IVParamsSpec parameter.
Encryption/Decryption Code (ArkTS):
// Encrypt message.
async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
let cipher = cryptoFramework.createCipher('SM4_128|CTR|NoPadding');
let smIV = '12345678';
let ivParamsSpec: cryptoFramework.IvParamsSpec = {
algName: "IvParamsSpec",
iv: { data: new Uint8Array(buffer.from(smIV, 'utf-8').buffer) }
};
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ivParamsSpec);
let encryptData = await cipher.doFinal(plainText);
return encryptData;
}
// Decrypt message.
async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
let decoder = cryptoFramework.createCipher('SM4_128|CTR|NoPadding');
let smIV = '12345678';
let ivParamsSpec: cryptoFramework.IvParamsSpec = {
algName: "IvParamsSpec",
iv: { data: new Uint8Array(buffer.from(smIV, 'utf-8').buffer) }
};
await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, ivParamsSpec);
let decryptData = await decoder.doFinal(cipherText);
return decryptData;
}
Error Message:
decrypt ok enData: VLhJHQ==
decrypt ok deDate: ��G
decrypt failed
Background Knowledge
The algorithm library currently provides 7 common encryption modes for SM4: ECB, CBC, CTR, OFB, CFB, CFB128, and GCM. Different encryption modes require specific parameters. For details, refer to ParamsSpec.
Troubleshooting Process
- Check if the parameters passed when creating the encryption/decryption instance are correct.
- Check if the parameters passed during the
initmethod of the encryption/decryption instance are correct. - Verify if the
IVParamsSpecparameter meets the requirements.
Analysis Conclusion
The IVParamsSpec parameter provided is 8 bytes long, but the IVParamsSpec parameter for encryption/decryption requires 16 bytes. The incorrect length of the IVParamsSpec parameter causes the encryption/decryption failure.
Solution
Update the IVParamsSpec initialization to use a 16-byte IV instead of 8 bytes. For example:
let smIV = '1234567890123456'; // 16-byte IV
Verification Result
After updating the IVParamsSpec to use a 16-byte IV instead of the previous 8-byte string, the encryption and decryption processes were re-executed.
- Before fix:
- Encryption succeeded.
- Decryption produced corrupted output and failed validation.
- After fix:
- Encryption succeeded with no error.
- Decryption successfully restored the original plaintext message.
- No error message occurred during the process.
Top comments (0)