• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Converting Binary Data into a Symmetric Key (ArkTS)
2
3<!--Kit: Crypto Architecture Kit-->
4<!--Subsystem: Security-->
5<!--Owner: @zxz--3-->
6<!--Designer: @lanming-->
7<!--Tester: @PAFT-->
8<!--Adviser: @zengyawen-->
9
10This topic uses 3DES and HMAC as an example to describe how to convert binary data into a symmetric key (**SymKey**). That is, convert a piece of external or internal binary data into a key object for subsequent operations, such as encryption and decryption.
11
12## Converting Binary Data into a 3DES Key
13
14For details about the algorithm specifications, see [3DES](crypto-sym-key-generation-conversion-spec.md#3des).
15
161. Obtain the 3DES binary key data and encapsulate it into a [DataBlob](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#datablob) object.
17
182. Call [cryptoFramework.createSymKeyGenerator](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatesymkeygenerator) with the string parameter **'3DES192'** to create a symmetric key generator (**SymKeyGenerator**) object for a 192-bit 3DES key.
19
203. Call [SymKeyGenerator.convertKey](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#convertkey-1) to convert the binary data into a symmetric key (**SymKey**).
21
224. Call [SymKey.getEncoded](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#getencoded) to obtain the binary data of the key.
23
24- Example: Convert binary data into a 192-bit 3DES key (using callback-based APIs).
25
26  ```ts
27  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
28  import { BusinessError } from '@kit.BasicServicesKit';
29
30  function genKeyMaterialBlob(): cryptoFramework.DataBlob {
31    let arr = [
32      0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
33      0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
34      0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // The key length is 192 bits, that is, 24 bytes.
35    let keyMaterial = new Uint8Array(arr);
36    return { data: keyMaterial };
37  }
38
39  function testConvertSymKey() {
40    // Create a SymKeyGenerator instance.
41    let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
42    // Convert the data into a symmetric key.
43    let keyMaterialBlob = genKeyMaterialBlob();
44    try {
45      symKeyGenerator.convertKey(keyMaterialBlob, (error, key) => {
46        if (error) {// If the service logic fails to be executed, the first parameter of the callback returns error information, that is, throw an exception asynchronously.
47          let e: BusinessError = error as BusinessError;
48          console.error(`convertKey error, ${e.code}, ${e.message}`);
49          return;
50        }
51        console.info('key algName:' + key.algName);
52        console.info('key format:' + key.format);
53        let encodedKey = key.getEncoded(); // Obtain the binary data of the symmetric key and output the data as a byte array. The length is 24 bytes.
54        console.info('key getEncoded hex: ' + encodedKey.data);
55      })
56    } catch (error) {// Throw an exception immediately when an error is detected during parameter check.
57      let e: BusinessError = error as BusinessError;
58      console.error(`convertKey failed, ${e.code}, ${e.message}`);
59    }
60  }
61  ```
62
63- Example using synchronous API [convertKeySync](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#convertkeysync12):
64  ```ts
65  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
66
67  function genKeyMaterialBlob(): cryptoFramework.DataBlob {
68    let arr = [
69      0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
70      0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
71      0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // The key length is 192 bits, that is, 24 bytes.
72    let keyMaterial = new Uint8Array(arr);
73    return { data: keyMaterial };
74  }
75
76  function testConvertSymKey() {
77    // Create a SymKeyGenerator instance.
78    let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
79    // Convert the data into a symmetric key.
80    let keyMaterialBlob = genKeyMaterialBlob();
81    let key = symKeyGenerator.convertKeySync(keyMaterialBlob);
82    let encodedKey = key.getEncoded(); // Obtain the binary data of the symmetric key and output the data as a byte array. The length is 24 bytes.
83    console.info('key getEncoded hex' + encodedKey.data);
84  }
85  ```
86
87## Converting Binary Data into an HMAC Key
88
89For details, see [HMAC](crypto-sym-key-generation-conversion-spec.md#hmac).
90
911. Obtain the HMAC binary key and encapsulate it into a **DataBlob** object.
92
932. Call [cryptoFramework.createSymKeyGenerator](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatesymkeygenerator) with the string parameter **'HMAC'** to create a symmetric key generator (**SymKeyGenerator**) object for an HMAC key of [1, 32768] bits.
94
953. Call [SymKeyGenerator.convertKey](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#convertkey-1) to convert the binary data into a symmetric key (**SymKey**).
96
974. Call [SymKey.getEncoded](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#getencoded) to obtain the binary data of the key.
98
99- Example using **await** to generate a HMAC key:
100
101  ```ts
102  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
103  import { buffer } from '@kit.ArkTS';
104
105  async function testConvertHmacKey() {
106    // The symmetric key length is 64 bytes (512 bits).
107    let keyMessage = '12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh';
108    let keyBlob: cryptoFramework.DataBlob = {
109      data : new Uint8Array(buffer.from(keyMessage, 'utf-8').buffer)
110    }
111    let symKeyGenerator = cryptoFramework.createSymKeyGenerator('HMAC');
112    let key = await symKeyGenerator.convertKey(keyBlob);
113    let encodedKey = key.getEncoded();
114    console.info('key encoded data:' + encodedKey.data);
115  }
116  ```
117
118- Example using synchronous API [convertKeySync](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#convertkeysync12):
119  ```ts
120  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
121  import { buffer } from '@kit.ArkTS';
122
123  function testConvertKeySync() {
124    // The symmetric key length is 64 bytes (512 bits).
125    let keyMessage = '12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh';
126    let keyBlob: cryptoFramework.DataBlob = {
127      data : new Uint8Array(buffer.from(keyMessage, 'utf-8').buffer)
128    }
129    let symKeyGenerator = cryptoFramework.createSymKeyGenerator('HMAC');
130    let key = symKeyGenerator.convertKeySync(keyBlob);
131    let encodedKey = key.getEncoded();
132    console.info('key encoded data:' + encodedKey.data);
133  }
134  ```
135