• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16// [Start ccm_encrypt_decrypt_aes_symkey_sync]
17import { cryptoFramework } from '@kit.CryptoArchitectureKit';
18import { buffer } from '@kit.ArkTS';
19
20function genCcmParamsSpec() {
21  let rand: cryptoFramework.Random = cryptoFramework.createRandom();
22  let ivBlob: cryptoFramework.DataBlob = rand.generateRandomSync(7);
23  let aadBlob: cryptoFramework.DataBlob = rand.generateRandomSync(8);
24  let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 12 bytes
25  let dataTag = new Uint8Array(arr);
26  let tagBlob: cryptoFramework.DataBlob = {
27    data: dataTag
28  };
29  // CCM的authTag在加密时从doFinal结果中获取,在解密时填入init函数的params参数中
30  let ccmParamsSpec: cryptoFramework.CcmParamsSpec = {
31    iv: ivBlob,
32    aad: aadBlob,
33    authTag: tagBlob,
34    algName: 'CcmParamsSpec'
35  };
36  return ccmParamsSpec;
37}
38
39let ccmParams = genCcmParamsSpec();
40
41// 加密消息
42function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
43  let cipher = cryptoFramework.createCipher('AES128|CCM');
44  cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ccmParams);
45  let encryptUpdate = cipher.updateSync(plainText);
46  // ccm模式加密doFinal时传入空,获得tag数据,并更新至ccmParams对象中。
47  ccmParams.authTag = cipher.doFinalSync(null);
48  return encryptUpdate;
49}
50
51// 解密消息
52function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
53  let decoder = cryptoFramework.createCipher('AES128|CCM');
54  decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, ccmParams);
55  let decryptUpdate = decoder.doFinalSync(cipherText);
56  return decryptUpdate;
57}
58
59function genSymKeyByData(symKeyData: Uint8Array) {
60  let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
61  let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
62  let symKey = aesGenerator.convertKeySync(symKeyBlob);
63  console.info('convertKeySync success');
64  return symKey;
65}
66
67function main() {
68  let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]);
69  let symKey = genSymKeyByData(keyData);
70  let message = 'This is a test';
71  let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
72  let encryptText = encryptMessage(symKey, plainText);
73  let decryptText = decryptMessage(symKey, encryptText);
74  if (plainText.data.toString() === decryptText.data.toString()) {
75    console.info('decrypt ok');
76    console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
77  } else {
78    console.error('decrypt failed');
79  }
80}
81// [End ccm_encrypt_decrypt_aes_symkey_sync]
82
83@Entry
84@Component
85struct Index {
86  @State message: string = 'Encryption Decryption Guidance Aes ArkTs';
87
88  build() {
89    Column({ space: 12 }) {
90      Text(this.message).fontSize(20).fontWeight(FontWeight.Bold)
91      Button($r('app.string.call_aes_ccm_synchronous'))
92        .width('70%')
93        .onClick(() => {
94          try {
95            main();
96            this.message = 'AES_CCMSynchronousSuccess';
97          } catch {
98            this.message = 'AES_CCMSynchronousFail';
99          }
100        })
101    }
102    .height('100%')
103    .width('100%')
104  }
105}