Generate SM2 Key Pair Using Key Parameters for Encryption and Decryption
Source: Dev.to
Question
In SM2 encryption and decryption, HarmonyOS requires ASN.1 serialized key data (91‑byte public key, 51‑byte private key). However, most SM2 key data is provided as raw, unserialized data (64‑byte public key, 32‑byte private key), which cannot be used directly.
How can raw SM2 keys be converted into ASN.1 serialized SM2 key pairs that are usable on the HarmonyOS platform?
Short Answer
Reconstruct the SM2 keys from the raw parameters by generating public and private keys using cryptoFramework with the appropriate ASN.1 specification.
Generate the SM2 public key from raw parameters
/**
* Generate SM2 public key based on public key parameters
* @param keyStr The general format of the public key parameter is 04 + x + y.
* @returns SM2 public key
*/
async function convertStrToPubKey(keyStr: string): Promise {
let pubKeyStr = keyStr.startsWith("04") ? keyStr.slice(2) : keyStr;
let pkPart1 = pubKeyStr.slice(0, pubKeyStr.length / 2);
let pkPart2 = pubKeyStr.slice(pubKeyStr.length / 2);
// Enter hexadecimal in the corresponding position
let pk: cryptoFramework.Point = {
x: BigInt("0x" + pkPart1),
y: BigInt("0x" + pkPart2),
};
// Public key object parameters
let pubKeySpec: cryptoFramework.ECCPubKeySpec = {
params: cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_sm2'),
pk: pk,
algName: "SM2",
specType: cryptoFramework.AsyKeySpecType.PUBLIC_KEY_SPEC,
};
let keypairGenerator = cryptoFramework.createAsyKeyGeneratorBySpec(pubKeySpec);
return await keypairGenerator.generatePubKey();
}
Generate the SM2 private key from raw parameters
/**
* Generate SM2 private key based on private key parameters
* @param keyStr The private key parameter is generally a 128‑bit string.
* @returns SM2 private key
*/
async function convertStrToPriKey(keyStr: string): Promise {
let sk = BigInt("0x" + keyStr);
// Private key object parameters
let priKeySpec: cryptoFramework.ECCPriKeySpec = {
params: cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_sm2'),
sk: sk,
algName: "SM2",
specType: cryptoFramework.AsyKeySpecType.PRIVATE_KEY_SPEC,
};
let keypairGenerator = cryptoFramework.createAsyKeyGeneratorBySpec(priKeySpec);
return await keypairGenerator.generatePriKey();
}
For more details, refer to the document SM2 Encryption and Decryption.
Applicable Scenarios
- When raw SM2 key data (64‑byte public key, 32‑byte private key) is provided.
- When HarmonyOS requires ASN.1 serialized key data (91‑byte public key, 51‑byte private key) for SM2 encryption and decryption.