使用AES对称密钥（CCM模式）加解密(ArkTS)
==========================

查看[对称密钥加解密算法规格：AES](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/crypto-sym-encrypt-decrypt-spec#aes)。

**加密**

1.  调用[cryptoFramework.createSymKeyGenerator](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#cryptoframeworkcreatesymkeygenerator)、[SymKeyGenerator.generateSymKey](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#generatesymkey-1)，生成密钥算法为AES、密钥长度为128位的对称密钥（SymKey）。
    
    如何生成AES对称密钥，开发者可参考下文示例，并结合[对称密钥生成和转换规格：AES](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/crypto-sym-key-generation-conversion-spec#aes)和[随机生成对称密钥](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/crypto-generate-sym-key-randomly)进行理解，参考文档与当前示例可能存在入参差异，请注意区分。
    
2.  调用[cryptoFramework.createCipher](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#cryptoframeworkcreatecipher)，指定字符串参数'AES128|CCM'，创建对称密钥为AES128、分组模式为CCM的Cipher实例，用于执行加密操作。
    
3.  调用[Cipher.init](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#init-1)，设置模式为加密（cryptoFramework.CryptoMode.ENCRYPT\_MODE），指定密钥（SymKey）和CCM模式对应的加密参数（CcmParamsSpec），初始化加密Cipher实例。
    
4.  调用[Cipher.update](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#update-1)，更新数据（明文）。
    
    当前单次update没有长度限制，开发者可以根据数据量决定如何调用update。
    
    ![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/ab/v3/2NAPSMiSQzi8errmOh-How/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260709T132401Z&HW-CC-Expire=86400&HW-CC-Sign=0914FB8B3ADD364B8DC8E07F4ACB376A991C3F304651E2A5188EFACFA1FC1F26)
    
    CCM模式不支持分段加解密。
    
5.  调用[Cipher.doFinal](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#dofinal-1)获取加密后的数据。
    
    *   由于已通过update传入数据，此处传入null。
    *   doFinal输出结果可能为null，访问具体数据前，需先判断结果是否为null，以避免异常。
6.  读取[CcmParamsSpec.authTag](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#ccmparamsspec)作为解密的认证信息。
    
    ![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/40/v3/AfPBuCqpRBmpBwn62y22Bg/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260709T132401Z&HW-CC-Expire=86400&HW-CC-Sign=1DE12CA7CDD2BA1916D5270F549FA13B373E4AC987A38EAF1AED3FC8FE4C7E9F)
    
    在CCM模式下，一次加密流程中，将每次update和最后doFinal的结果拼接起来，会得到“密文 + authTag”, authTag为末尾的12字节。其余部分均为密文。如果doFinal的data参数传入null，则doFinal的结果就是authTag。
    

**解密**

1.  调用[cryptoFramework.createCipher](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#cryptoframeworkcreatecipher)，指定字符串参数'AES128|CCM'，创建对称密钥为AES128、分组模式为CCM的Cipher实例，用于完成解密操作。
    
2.  调用[Cipher.init](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#init-1)，设置模式为解密（cryptoFramework.CryptoMode.DECRYPT\_MODE），指定密钥（SymKey）和CCM模式对应的解密参数（CcmParamsSpec），初始化解密Cipher实例。
    
3.  调用[Cipher.doFinal](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#dofinal-1)，获取解密后的数据。
    

*   异步方法示例：
    
    import { cryptoFramework } from '@kit.CryptoArchitectureKit';
    import { buffer } from '@kit.ArkTS';
    
    function genCcmParamsSpec() {
      let rand: cryptoFramework.Random = cryptoFramework.createRandom();
      let ivBlob: cryptoFramework.DataBlob = rand.generateRandomSync(7);
      let aadBlob: cryptoFramework.DataBlob = rand.generateRandomSync(8);
      let arr = \[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\]; // 12 bytes
      let dataTag = new Uint8Array(arr);
      let tagBlob: cryptoFramework.DataBlob = {
        data: dataTag
      };
      // CCM的authTag在加密时从doFinal结果中获取，在解密时填入init函数的params参数中
      let ccmParamsSpec: cryptoFramework.CcmParamsSpec = {
        iv: ivBlob,
        aad: aadBlob,
        authTag: tagBlob,
        algName: 'CcmParamsSpec'
      };
      return ccmParamsSpec;
    }
    
    let ccmParams = genCcmParamsSpec();
    
    // 加密消息
    async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
      let cipher = cryptoFramework.createCipher('AES128|CCM');
      await cipher.init(cryptoFramework.CryptoMode.ENCRYPT\_MODE, symKey, ccmParams);
      let encryptUpdate = await cipher.update(plainText);
      // ccm模式加密doFinal时传入空，获得tag数据，并更新至ccmParams对象中。
      ccmParams.authTag = await cipher.doFinal(null);
      return encryptUpdate;
    }
    
    // 解密消息
    async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
      let decoder = cryptoFramework.createCipher('AES128|CCM');
      await decoder.init(cryptoFramework.CryptoMode.DECRYPT\_MODE, symKey, ccmParams);
      let decryptUpdate = await decoder.doFinal(cipherText);
      return decryptUpdate;
    }
    
    async function genSymKeyByData(symKeyData: Uint8Array) {
      let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
      let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
      let symKey = await aesGenerator.convertKey(symKeyBlob);
      console.info('convertKey result: success.');
      return symKey;
    }
    
    async function main() {
      let keyData = new Uint8Array(\[83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159\]);
      let symKey = await genSymKeyByData(keyData);
      let message = 'This is a test';
      let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
      let encryptText = await encryptMessagePromise(symKey, plainText);
      let decryptText = await decryptMessagePromise(symKey, encryptText);
      if (plainText.data.toString() === decryptText.data.toString()) {
        console.info('decrypt ok.');
        console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
      } else {
        console.error('decrypt failed.');
      }
    }
    
*   同步方法示例：
    
    import { cryptoFramework } from '@kit.CryptoArchitectureKit';
    import { buffer } from '@kit.ArkTS';
    
    function genCcmParamsSpec() {
      let rand: cryptoFramework.Random = cryptoFramework.createRandom();
      let ivBlob: cryptoFramework.DataBlob = rand.generateRandomSync(7);
      let aadBlob: cryptoFramework.DataBlob = rand.generateRandomSync(8);
      let arr = \[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\]; // 12 bytes
      let dataTag = new Uint8Array(arr);
      let tagBlob: cryptoFramework.DataBlob = {
        data: dataTag
      };
      // CCM的authTag在加密时从doFinal结果中获取，在解密时填入init函数的params参数中
      let ccmParamsSpec: cryptoFramework.CcmParamsSpec = {
        iv: ivBlob,
        aad: aadBlob,
        authTag: tagBlob,
        algName: 'CcmParamsSpec'
      };
      return ccmParamsSpec;
    }
    
    let ccmParams = genCcmParamsSpec();
    
    // 加密消息
    function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
      let cipher = cryptoFramework.createCipher('AES128|CCM');
      cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT\_MODE, symKey, ccmParams);
      let encryptUpdate = cipher.updateSync(plainText);
      // ccm模式加密doFinal时传入空，获得tag数据，并更新至ccmParams对象中。
      ccmParams.authTag = cipher.doFinalSync(null);
      return encryptUpdate;
    }
    
    // 解密消息
    function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
      let decoder = cryptoFramework.createCipher('AES128|CCM');
      decoder.initSync(cryptoFramework.CryptoMode.DECRYPT\_MODE, symKey, ccmParams);
      let decryptUpdate = decoder.doFinalSync(cipherText);
      return decryptUpdate;
    }
    
    function genSymKeyByData(symKeyData: Uint8Array) {
      let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
      let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
      let symKey = aesGenerator.convertKeySync(symKeyBlob);
      console.info('convertKeySync result: success.');
      return symKey;
    }
    
    function main() {
      let keyData = new Uint8Array(\[83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159\]);
      let symKey = genSymKeyByData(keyData);
      let message = 'This is a test';
      let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
      let encryptText = encryptMessage(symKey, plainText);
      let decryptText = decryptMessage(symKey, encryptText);
      if (plainText.data.toString() === decryptText.data.toString()) {
        console.info('decrypt ok.');
        console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
      } else {
        console.error('decrypt failed.');
      }
    }