• 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// [Start use_dh_for_key_negotiation_async]
16import { cryptoFramework } from '@kit.CryptoArchitectureKit';
17
18async function dhAwait() {
19  let keyGen = cryptoFramework.createAsyKeyGenerator('DH_modp1536');
20  // 随机生成公私钥对A
21  let keyPairA = await keyGen.generateKeyPair();
22  // 随机生成规格一致的公私钥对B
23  let keyPairB = await keyGen.generateKeyPair();
24  let keyAgreement = cryptoFramework.createKeyAgreement('DH_modp1536');
25  // 使用A的公钥和B的私钥进行密钥协商
26  let secret1 = await keyAgreement.generateSecret(keyPairB.priKey, keyPairA.pubKey);
27  // 使用A的私钥和B的公钥进行密钥协商
28  let secret2 = await keyAgreement.generateSecret(keyPairA.priKey, keyPairB.pubKey);
29  // 两种协商的结果应当一致
30  if (secret1.data.toString() === secret2.data.toString()) {
31    console.info('DH success');
32    console.info('DH output is ' + secret1.data);
33  } else {
34    console.error('DH result is not equal');
35  }
36}
37// [End use_dh_for_key_negotiation_async]
38
39@Entry
40@Component
41struct Index {
42  @State message: string = 'DH Async';
43
44  build() {
45    Column({ space: 12 }) {
46      Text(this.message).fontSize(20).fontWeight(FontWeight.Bold)
47      Button($r('app.string.call_dh_async'))
48        .width('70%')
49        .onClick(async () => {
50          try {
51            await dhAwait();
52            this.message = 'DH Async Success';
53          } catch {
54            this.message = 'DH Async Fail';
55          }
56        })
57    }
58    .height('100%')
59    .width('100%')
60  }
61}