DEV Community

HarmonyOS
HarmonyOS

Posted on

Conversion of 16 encoded strings to Unit8Array

Read the original article:Conversion of 16 encoded strings to Unit8Array

Problem Description

When using the SM2 algorithm for encryption, developers may encounter difficulties converting a hexadecimal encoded string into a Uint8Array type, which is required for proper data processing.

Background Knowledge

The SM2 algorithm is a Chinese public key cryptographic standard based on elliptic curves. It often requires input and output data to be processed in binary formats such as Uint8Array. However, many cryptographic APIs and libraries represent data in hexadecimal strings, leading to compatibility issues.

Troubleshooting Process
  1. Attempted to pass the hexadecimal string directly to the SM2 encryption method.
  2. Observed that the algorithm did not accept the string type and returned errors or produced invalid results.
  3. Investigated whether a conversion method was required between hex and Uint8Array.
  4. Identified the need to implement a reliable utility function for conversion.
Analysis Conclusion

The root cause of the issue is the data encoding mismatch: SM2 requires binary data (Uint8Array) but receives hexadecimal strings. Without conversion, the encryption process fails.

cke_11209.png

Solution

To resolve the issue, implement utility functions to convert between hexadecimal strings and Uint8Array:

These functions ensure proper conversion, making the data compatible with SM2 encryption/decryption.

Verification Result

After applying the conversion functions, the SM2 encryption process successfully accepted the converted input and returned the expected results. No further errors were observed.

For details, see Document Data Encoding Format Differences.

Written by Taha Enes Kon

Top comments (0)