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

从API版本26.0.0开始，[AES](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/crypto-sym-encrypt-decrypt-spec#aes)对称密钥加解密支持使用XTS分组模式。

**密钥生成**

调用[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、密钥长度为256位的对称密钥（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)理解，参考文档与当前示例可能存在入参差异，请在阅读时注意区分。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/a9/v3/yOPpCyRyT2qdy_l7yyXtog/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073359Z&HW-CC-Expire=86400&HW-CC-Sign=A73A264505B4122538BEF66A8F441ED8CD9ACC369747BC64A2A47E9D3948A746)

AES对称密钥（XTS模式）加解密时，对称密钥长度需要是标准AES密钥的2倍。且只支持创建AES-128、AES-256的cipher实例进行加解密。

示例代码中创建AES256的对称密钥，AES128的cipher实例进行加解密。

**加密**

1.  调用[cryptoFramework.createCipher](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#cryptoframeworkcreatecipher)，指定字符串参数'AES128|XTS'，创建对称密钥类型为AES128、分组模式为XTS的Cipher实例，用于完成加密操作。
    
2.  调用[Cipher.init](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#init-1)，设置模式为加密（cryptoFramework.CryptoMode.ENCRYPT\_MODE），指定加密密钥（SymKey）和XTS模式对应的加密参数（IvParamsSpec），初始化加密Cipher实例。
    
3.  当加密内容长度较短时，可以直接调用 [Cipher.doFinal](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#dofinal-1) 而无需调用update，以获取加密后的数据。
    

**解密**

1.  调用[cryptoFramework.createCipher](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#cryptoframeworkcreatecipher)，指定字符串参数'AES128|XTS'，创建对称密钥类型为AES128、分组模式为XTS的Cipher实例，用于完成解密操作。
    
2.  调用[Cipher.init](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#init-1)，设置模式为解密（cryptoFramework.CryptoMode.DECRYPT\_MODE），指定解密密钥（SymKey）和XTS模式对应的解密参数（IvParamsSpec），初始化解密Cipher实例。
    
3.  当解密内容长度较短时，可以省略调用update，直接调用[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 generateRandom(len: number) {
      let rand = cryptoFramework.createRandom();
      let generateRandSync = rand.generateRandomSync(len);
      return generateRandSync;
    }
    
    function genIvParamsSpec() {
      let ivBlob = generateRandom(16);
      let ivParamsSpec: cryptoFramework.IvParamsSpec = {
        algName: 'IvParamsSpec',
        iv: ivBlob
      };
      return ivParamsSpec;
    }
    
    let iv = genIvParamsSpec();
    
    // 加密消息
    async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
      let cipher = cryptoFramework.createCipher('AES128|XTS');
      await cipher.init(cryptoFramework.CryptoMode.ENCRYPT\_MODE, symKey, iv);
      let cipherData = await cipher.doFinal(plainText);
      return cipherData;
    }
    
    // 解密消息
    async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
      let decoder = cryptoFramework.createCipher('AES128|XTS');
      await decoder.init(cryptoFramework.CryptoMode.DECRYPT\_MODE, symKey, iv);
      let decryptData = await decoder.doFinal(cipherText);
      return decryptData;
    }
    
    export async function aesXTS() : Promise<string> {
      try {
        let symGenerator = cryptoFramework.createSymKeyGenerator('AES256')
        let symKey = await symGenerator.generateSymKey()
        let message = 'This is a xts encrypt decrypt 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');
        }
        return 'success';
      } catch (error) {
        console.error('xts decrypt failed. error: ' + error);
        return 'fail';
      }
    }
    
*   同步方法示例：
    
    import { cryptoFramework } from '@kit.CryptoArchitectureKit';
    import { buffer } from '@kit.ArkTS';
    
    function generateRandom(len: number) {
      let rand = cryptoFramework.createRandom();
      let generateRandSync = rand.generateRandomSync(len);
      return generateRandSync;
    }
    
    function genIvParamsSpec() {
      let ivBlob = generateRandom(16);
      let ivParamsSpec: cryptoFramework.IvParamsSpec = {
        algName: 'IvParamsSpec',
        iv: ivBlob
      };
      return ivParamsSpec;
    }
    
    let iv = genIvParamsSpec();
    
    // 加密消息
    function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
      let cipher = cryptoFramework.createCipher('AES128|XTS');
      cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT\_MODE, symKey, iv);
      let cipherData = cipher.doFinalSync(plainText);
      return cipherData;
    }
    
    // 解密消息
    function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
      let decoder = cryptoFramework.createCipher('AES128|XTS');
      decoder.initSync(cryptoFramework.CryptoMode.DECRYPT\_MODE, symKey, iv);
      let decryptData = decoder.doFinalSync(cipherText);
      return decryptData;
    }
    
    export function aesXTS() : string {
      try {
        let symGenerator = cryptoFramework.createSymKeyGenerator('AES256')
        let symKey = symGenerator.generateSymKeySync()
        let message = 'This is a xts encrypt decrypt 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.');
        }
        return 'success';
      } catch (error) {
        console.error('xts decrypt failed. error: ' + error);
        return 'fail';
      }
    }