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