harmony SM4 实现相对简单直观,开发流程大致如下:
static async encrypt(password: Uint8Array, clearText: Uint8Array, iv: Uint8Array): Promise<Uint8Array> {
try {
//1.创建密钥生成器
let sm4Generator = cryptoFramework.createSymKeyGenerator('SM4_128')
//2.使用密钥生成器将密钥转换成 cryptoFramework.SymKey
let symKey = await sm4Generator.convertKey({ data: password })
//3.生成 iv等算法参数
let paramsSpec: cryptoFramework.IvParamsSpec = { iv: { data: iv }, algName: "IvParamsSpec" }
//4.创建cipher
let cipher = cryptoFramework.createCipher("SM4_128|CBC|PKCS5")
//5.init cipher
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, paramsSpec)
//6.加密
let encryptText = await cipher.doFinal({ data: clearText })
return encryptText.data
} catch (e) {
return new Uint8Array()
}
}
static async decrypt(password: Uint8Array, cipherText: Uint8Array, iv: Uint8Array): Promise<Uint8Array> {
try {
//1.创建密钥生成器
let sm4Generator = cryptoFramework.createSymKeyGenerator('SM4_128')
//2.使用密钥生成器将密钥转换成 cryptoFramework.SymKey
let symKey = await sm4Generator.convertKey({ data: password })
//3.生成 iv等算法参数
let paramsSpec: cryptoFramework.IvParamsSpec = { iv: { data: iv }, algName: "IvParamsSpec" }
//4.创建cipher
let cipher = cryptoFramework.createCipher("SM4_128|CBC|PKCS5")
//5.init cipher
await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, paramsSpec)
//6.解密
let clearText = await cipher.doFinal({ data: cipherText})
//8.返回解密结果
return clearText.data
} catch (e) {
return new Uint8Array()
}
}