• 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
16import { HiLog } from '../HiLog';
17import { isInvalidStr } from '../FileUtils/utils';
18import { huks } from '@kit.UniversalKeystoreKit';
19
20const TAG: string = 'HuksCipherUtils';
21
22export default class HuksCipherUtils {
23  public static async isKeyExist(keyAlias: string): Promise<boolean> {
24    if (isInvalidStr(keyAlias)) {
25      HiLog.error(TAG, 'Input key alias is invalid.');
26      return false;
27    }
28    let emptyOptions: huks.HuksOptions = {
29      properties: []
30    };
31    try {
32      let isKeyExist = await huks.isKeyItemExist(keyAlias, emptyOptions);
33      HiLog.info(TAG, `isKeyItemExist success, isKeyExist: ${isKeyExist}.`);
34      return isKeyExist;
35    } catch (err) {
36      HiLog.error(TAG, `IsKeyExist failed: ${JSON.stringify(err)}`);
37    }
38    return false;
39  }
40
41  public static async generateKey(keyAlias: string, options: huks.HuksOptions): Promise<boolean> {
42    if (isInvalidStr(keyAlias)) {
43      HiLog.error(TAG, 'keyAlias is invalid.');
44      return false;
45    }
46    if (!options) {
47      HiLog.error(TAG, 'HuksOptions is invalid.');
48      return false;
49    }
50    try {
51      await huks.generateKeyItem(keyAlias, options);
52      HiLog.info(TAG, 'Generate key success!');
53      return true;
54    } catch (err) {
55      HiLog.error(TAG, `generateKey failed: ${JSON.stringify(err)}`);
56    }
57    return false;
58  }
59
60  public static async deleteKey(keyAlias: string): Promise<void> {
61    if (isInvalidStr(keyAlias)) {
62      HiLog.error(TAG, 'keyAlias is invalid.');
63      return;
64    }
65    let emptyOptions: huks.HuksOptions = {
66      properties: []
67    };
68    try {
69      await huks.deleteKeyItem(keyAlias, emptyOptions);
70      HiLog.info(TAG, 'deleteKeyItem success.');
71    } catch (err) {
72      HiLog.error(TAG, `deleteKey failed: ${JSON.stringify(err)}`);
73    }
74  }
75
76  public static async encrypt(keyAlias: string, plainData: Uint8Array,
77    params: huks.HuksParam[]): Promise<Uint8Array | undefined> {
78    if (isInvalidStr(keyAlias)) {
79      HiLog.error(TAG, 'keyAlias is invalid.');
80      return undefined;
81    }
82    if (!plainData || plainData.length === 0) {
83      HiLog.error(TAG, 'plainData is invalid.');
84      return undefined;
85    }
86    if (!params) {
87      HiLog.error(TAG, 'HuksParam is invalid.');
88      return undefined;
89    }
90    let option: huks.HuksOptions = {
91      properties: params,
92      inData: plainData
93    };
94    let handle: number | undefined;
95    let resultData: Uint8Array | undefined;
96    try {
97      let sessionHandle = await huks.initSession(keyAlias, option);
98      handle = sessionHandle.handle;
99      let sessionResult = await huks.finishSession(handle, option);
100      resultData = sessionResult.outData;
101    } catch (err) {
102      HiLog.error(TAG, `Encrypt data failed: ${JSON.stringify(err)}`);
103      if (handle) {
104        HuksCipherUtils.abort(handle, option);
105      }
106    }
107    return resultData;
108  }
109
110  public static async decrypt(keyAlias: string, cipherData: Uint8Array,
111    params: huks.HuksParam[]): Promise<Uint8Array | undefined> {
112    if (isInvalidStr(keyAlias)) {
113      HiLog.error(TAG, 'keyAlias is invalid.');
114      return undefined;
115    }
116    if (!cipherData || cipherData.length === 0) {
117      HiLog.error(TAG, 'cipherData is invalid.');
118      return undefined;
119    }
120    if (!params) {
121      HiLog.error(TAG, 'HuksParam is invalid.');
122      return undefined;
123    }
124    let option: huks.HuksOptions = {
125      properties: params,
126      inData: cipherData
127    };
128    let handle: number | undefined;
129    let resultData: Uint8Array | undefined;
130    try {
131      let sessionHandle = await huks.initSession(keyAlias, option);
132      handle = sessionHandle.handle;
133      let sessionResult = await huks.finishSession(handle, option);
134      resultData = sessionResult.outData;
135    } catch (err) {
136      HiLog.error(TAG, `Decrypt data failed: ${JSON.stringify(err)}`);
137      if (handle) {
138        HuksCipherUtils.abort(handle, option);
139      }
140    }
141    return resultData;
142  }
143
144  private static async abort(handle: number, options: huks.HuksOptions): Promise<void> {
145    try {
146      await huks.abortSession(handle, options);
147    } catch (err) {
148      HiLog.error(TAG, `Abort session failed: ${JSON.stringify(err)}`);
149    }
150  }
151}