1# Importing a Key in Ciphertext (C/C++) 2 3 4This topic walks you through on how to import an ECDH key pair. However, the example does not cover the operations such as [key generation](huks-key-generation-overview.md) and [key agreement](huks-key-agreement-overview.md) of the service side. 5 6 7For details about the scenarios and supported algorithm specifications, see [Supported Algorithms](huks-key-import-overview.md#supported-algorithms). 8 9## Add the dynamic library in the CMake script. 10```txt 11 target_link_libraries(entry PUBLIC libhuks_ndk.z.so) 12``` 13 14## How to Develop 15 161. Convert the key to be imported from device A (device from which the key is imported) to [HUKS key material format](huks-concepts.md#key material format) **To_Import_Key**. (This step applies only to asymmetric key pairs. If the key to be imported is a symmetric key, skip over this step.) 17 182. Generate an asymmetric key pair **Wrapping_Key** (public key **Wrapping_Pk** and private key **Wrapping_Sk**) with the purpose of **HUKS_KEY_PURPOSE_UNWRAP** for device B (device to which the key is imported), and export the public key **Wrapping_Pk** of **Wrapping_Key** and save it. The asymmetric key pair **Wrapping_Key** is used for key agreement in the encrypted import process. 19 203. Use the same algorithm to generate an asymmetric key pair **Caller_Key** (public key **Caller_Pk** and private key **Caller_Sk**) with the purpose of **HUKS_KEY_PURPOSE_UNWRAP** for device A, and export the public key **Caller_Pk** of **Caller_Key** and save it. The asymmetric key pair **Caller_Key** is used for key agreement in the encrypted import process. 21 224. Generate a symmetric key **Caller_Kek** for device A. This key is used to encrypt **To_Import_Key**. 23 245. Perform key agreement with the private key **Caller_Sk** in **Caller_Key** of device A and the public key **Wrapping_Pk** in **Wrapping_Key** of device B to yield a **Shared_Key**. 25 266. Use **Caller_Kek** to encrypt **To_Import_Key** of device A and generate **To_Import_Key_Enc**. 27 287. Use **Shared_Key** to encrypt **Caller_Kek** of device A and generate **Caller_Kek_Enc**. 29 308. Encapsulate the key material **Caller_Pk**, **Caller_Kek_Enc**, and **To_Import_Key_Enc** of device A, and sends it to device B. For details about the format of the key material to be imported, see [Key Material Format for Encrypted Import](huks-key-import-overview.md#key-material-format-for-encrypted-import). 31 329. Import the encrypted key material to device B. 33 3410. Delete the intermediate keys (keys used for encrypting the key to import) from devices A and B. 35 36```c++ 37#include "napi/native_api.h" 38#include "huks/native_huks_api.h" 39#include "huks/native_huks_param.h" 40#include <algorithm> 41OH_Huks_Result InitParamSet(struct OH_Huks_ParamSet **paramSet, const struct OH_Huks_Param *params, 42 uint32_t paramCount) { 43 OH_Huks_Result ret = OH_Huks_InitParamSet(paramSet); 44 if (ret.errorCode != OH_HUKS_SUCCESS) { 45 return ret; 46 } 47 ret = OH_Huks_AddParams(*paramSet, params, paramCount); 48 if (ret.errorCode != OH_HUKS_SUCCESS) { 49 OH_Huks_FreeParamSet(paramSet); 50 return ret; 51 } 52 ret = OH_Huks_BuildParamSet(paramSet); 53 if (ret.errorCode != OH_HUKS_SUCCESS) { 54 OH_Huks_FreeParamSet(paramSet); 55 return ret; 56 } 57 return ret; 58} 59struct HksImportWrappedKeyTestParams { 60 // server key, for real 61 struct OH_Huks_Blob *wrappingKeyAlias; 62 struct OH_Huks_ParamSet *genWrappingKeyParamSet; 63 uint32_t publicKeySize; 64 struct OH_Huks_Blob *callerKeyAlias; 65 struct OH_Huks_ParamSet *genCallerKeyParamSet; 66 struct OH_Huks_Blob *callerKekAlias; 67 struct OH_Huks_Blob *callerKek; 68 struct OH_Huks_ParamSet *importCallerKekParamSet; 69 struct OH_Huks_Blob *callerAgreeKeyAlias; 70 struct OH_Huks_ParamSet *agreeParamSet; 71 struct OH_Huks_ParamSet *importWrappedKeyParamSet; 72 struct OH_Huks_Blob *importedKeyAlias; 73 struct OH_Huks_Blob *importedPlainKey; 74 uint32_t keyMaterialLen; 75}; 76static const uint32_t IV_SIZE = 16; 77static uint8_t IV[IV_SIZE] = "babababababab"; // Test data only. The value must be different each time. 78static const uint32_t WRAPPED_KEY_IV_SIZE = 16; 79static uint8_t WRAPPED_KEY_IV[IV_SIZE] = "bababababababab"; // Test data only. The value must be different each time. 80static const uint32_t AAD_SIZE = 16; 81static uint8_t AAD[AAD_SIZE] = "abababababababa"; // Test data only. The value must be different each time. 82static const uint32_t NONCE_SIZE = 12; 83static uint8_t NONCE[NONCE_SIZE] = "hahahahahah"; // Test data only. The value must be different each time. 84static const uint32_t AEAD_TAG_SIZE = 16; 85static const uint32_t X25519_256_SIZE = 256; 86static struct OH_Huks_Blob g_wrappingKeyAliasAes256 = {.size = (uint32_t)strlen("test_wrappingKey_x25519_aes256"), 87 .data = (uint8_t *)"test_wrappingKey_x25519_aes256"}; 88static struct OH_Huks_Blob g_callerKeyAliasAes256 = {.size = (uint32_t)strlen("test_caller_key_x25519_aes256"), 89 .data = (uint8_t *)"test_caller_key_x25519_aes256"}; 90static struct OH_Huks_Blob g_callerKekAliasAes256 = {.size = (uint32_t)strlen("test_caller_kek_x25519_aes256"), 91 .data = (uint8_t *)"test_caller_kek_x25519_aes256"}; 92static struct OH_Huks_Blob g_callerAes256Kek = {.size = (uint32_t)strlen("This is kek to encrypt plain key"), 93 .data = (uint8_t *)"This is kek to encrypt plain key"}; 94static struct OH_Huks_Blob g_callerAgreeKeyAliasAes256 = {.size = 95 (uint32_t)strlen("test_caller_agree_key_x25519_aes256"), 96 .data = (uint8_t *)"test_caller_agree_key_x25519_aes256"}; 97static struct OH_Huks_Blob g_importedKeyAliasAes256 = {.size = (uint32_t)strlen("test_import_key_x25519_aes256"), 98 .data = (uint8_t *)"test_import_key_x25519_aes256"}; 99static struct OH_Huks_Blob g_importedAes256PlainKey = {.size = (uint32_t)strlen("This is plain key to be imported"), 100 .data = (uint8_t *)"This is plain key to be imported"}; 101static struct OH_Huks_Param g_importWrappedAes256Params[] = { 102 {.tag = OH_HUKS_TAG_ALGORITHM, .uint32Param = OH_HUKS_ALG_AES}, 103 {.tag = OH_HUKS_TAG_PURPOSE, .uint32Param = OH_HUKS_KEY_PURPOSE_ENCRYPT | OH_HUKS_KEY_PURPOSE_DECRYPT}, 104 {.tag = OH_HUKS_TAG_KEY_SIZE, .uint32Param = OH_HUKS_AES_KEY_SIZE_256}, 105 {.tag = OH_HUKS_TAG_PADDING, .uint32Param = OH_HUKS_PADDING_NONE}, 106 {.tag = OH_HUKS_TAG_BLOCK_MODE, .uint32Param = OH_HUKS_MODE_GCM}, 107 {.tag = OH_HUKS_TAG_DIGEST, .uint32Param = OH_HUKS_DIGEST_NONE}, 108 {.tag = OH_HUKS_TAG_UNWRAP_ALGORITHM_SUITE, .uint32Param = OH_HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING}, 109 {.tag = OH_HUKS_TAG_ASSOCIATED_DATA, 110 .blob = {.size = AAD_SIZE, .data = (uint8_t *)AAD}}, // Test data only. The value varies with the caller information. 111 {.tag = OH_HUKS_TAG_NONCE, 112 .blob = {.size = NONCE_SIZE, .data = (uint8_t *)NONCE}}}; // Test data only. The value must be different each time. 113static const uint32_t g_x25519PubKeySize = 32; 114static struct OH_Huks_Param g_genWrappingKeyParams[] = { 115 {.tag = OH_HUKS_TAG_ALGORITHM, .uint32Param = OH_HUKS_ALG_X25519}, 116 {.tag = OH_HUKS_TAG_PURPOSE, .uint32Param = OH_HUKS_KEY_PURPOSE_UNWRAP}, 117 {.tag = OH_HUKS_TAG_KEY_SIZE, .uint32Param = OH_HUKS_CURVE25519_KEY_SIZE_256}}; 118static struct OH_Huks_Param g_genCallerX25519Params[] = { 119 {.tag = OH_HUKS_TAG_ALGORITHM, .uint32Param = OH_HUKS_ALG_X25519}, 120 {.tag = OH_HUKS_TAG_PURPOSE, .uint32Param = OH_HUKS_KEY_PURPOSE_AGREE}, 121 {.tag = OH_HUKS_TAG_KEY_SIZE, .uint32Param = OH_HUKS_CURVE25519_KEY_SIZE_256}}; 122static struct OH_Huks_Param g_importParamsCallerKek[] = { 123 {.tag = OH_HUKS_TAG_ALGORITHM, .uint32Param = OH_HUKS_ALG_AES}, 124 {.tag = OH_HUKS_TAG_PURPOSE, .uint32Param = OH_HUKS_KEY_PURPOSE_ENCRYPT}, 125 {.tag = OH_HUKS_TAG_KEY_SIZE, .uint32Param = OH_HUKS_AES_KEY_SIZE_256}, 126 {.tag = OH_HUKS_TAG_PADDING, .uint32Param = OH_HUKS_PADDING_NONE}, 127 {.tag = OH_HUKS_TAG_BLOCK_MODE, .uint32Param = OH_HUKS_MODE_GCM}, 128 {.tag = OH_HUKS_TAG_DIGEST, .uint32Param = OH_HUKS_DIGEST_NONE}, 129 {.tag = OH_HUKS_TAG_IV, 130 .blob = {.size = WRAPPED_KEY_IV_SIZE, 131 .data = (uint8_t *)WRAPPED_KEY_IV}}}; // Test data only. The value must be different each time. 132static struct OH_Huks_Param g_callerAgreeParams[] = { 133 {.tag = OH_HUKS_TAG_ALGORITHM, .uint32Param = OH_HUKS_ALG_X25519}, 134 {.tag = OH_HUKS_TAG_PURPOSE, .uint32Param = OH_HUKS_KEY_PURPOSE_AGREE}, 135 {.tag = OH_HUKS_TAG_KEY_SIZE, .uint32Param = OH_HUKS_CURVE25519_KEY_SIZE_256}}; 136static struct OH_Huks_Param g_aesKekEncryptParams[] = { 137 {.tag = OH_HUKS_TAG_ALGORITHM, .uint32Param = OH_HUKS_ALG_AES}, 138 {.tag = OH_HUKS_TAG_PURPOSE, .uint32Param = OH_HUKS_KEY_PURPOSE_ENCRYPT}, 139 {.tag = OH_HUKS_TAG_KEY_SIZE, .uint32Param = OH_HUKS_AES_KEY_SIZE_256}, 140 {.tag = OH_HUKS_TAG_PADDING, .uint32Param = OH_HUKS_PADDING_NONE}, 141 {.tag = OH_HUKS_TAG_BLOCK_MODE, .uint32Param = OH_HUKS_MODE_GCM}, 142 {.tag = OH_HUKS_TAG_DIGEST, .uint32Param = OH_HUKS_DIGEST_NONE}, 143 {.tag = OH_HUKS_TAG_ASSOCIATED_DATA, 144 .blob = {.size = AAD_SIZE, .data = (uint8_t *)AAD}}, // Test data only. The value varies with the caller information. 145 {.tag = OH_HUKS_TAG_NONCE, 146 .blob = {.size = NONCE_SIZE, .data = (uint8_t *)NONCE}}}; // Test data only. The value must be different each time. 147static struct OH_Huks_Param g_importAgreeKeyParams[] = { 148 {.tag = OH_HUKS_TAG_ALGORITHM, .uint32Param = OH_HUKS_ALG_AES}, 149 {.tag = OH_HUKS_TAG_PURPOSE, .uint32Param = OH_HUKS_KEY_PURPOSE_ENCRYPT}, 150 {.tag = OH_HUKS_TAG_KEY_SIZE, .uint32Param = OH_HUKS_AES_KEY_SIZE_256}, 151 {.tag = OH_HUKS_TAG_PADDING, .uint32Param = OH_HUKS_PADDING_NONE}, 152 {.tag = OH_HUKS_TAG_BLOCK_MODE, .uint32Param = OH_HUKS_MODE_GCM}, 153 {.tag = OH_HUKS_TAG_DIGEST, .uint32Param = OH_HUKS_DIGEST_NONE}, 154 {.tag = OH_HUKS_TAG_IV, 155 .blob = {.size = IV_SIZE, .data = (uint8_t *)IV}}}; // Test data only. The value must be different each time. 156OH_Huks_Result HuksAgreeKey(const struct OH_Huks_ParamSet *paramSet, const struct OH_Huks_Blob *keyAlias, 157 const struct OH_Huks_Blob *peerPublicKey, struct OH_Huks_Blob *agreedKey) { 158 uint8_t temp[10] = {0}; 159 struct OH_Huks_Blob inData = {sizeof(temp), temp}; 160 uint8_t handleU[sizeof(uint64_t)] = {0}; 161 struct OH_Huks_Blob handle = {sizeof(uint64_t), handleU}; 162 OH_Huks_Result ret = OH_Huks_InitSession(keyAlias, paramSet, &handle, nullptr); 163 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 164 return ret; 165 } 166 uint8_t outDataU[1024] = {0}; 167 struct OH_Huks_Blob outDataUpdate = {1024, outDataU}; 168 ret = OH_Huks_UpdateSession(&handle, paramSet, peerPublicKey, &outDataUpdate); 169 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 170 return ret; 171 } 172 ret = OH_Huks_FinishSession(&handle, paramSet, &inData, agreedKey); 173 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 174 return ret; 175 } 176 return ret; 177} 178OH_Huks_Result MallocAndCheckBlobData(struct OH_Huks_Blob *blob, const uint32_t blobSize) { 179 struct OH_Huks_Result ret; 180 ret.errorCode = OH_HUKS_SUCCESS; 181 blob->data = (uint8_t *)malloc(blobSize); 182 if (blob->data == NULL) { 183 ret.errorCode = OH_HUKS_ERR_CODE_INTERNAL_ERROR; 184 } 185 return ret; 186} 187static const uint32_t TIMES = 4; 188static const uint32_t MAX_UPDATE_SIZE = 64; 189static const uint32_t MAX_OUTDATA_SIZE = MAX_UPDATE_SIZE * TIMES; 190#define HUKS_FREE_BLOB(blob) \ 191 do { \ 192 if ((blob).data != nullptr) { \ 193 free((blob).data); \ 194 (blob).data = nullptr; \ 195 } \ 196 (blob).size = 0; \ 197 } while (0) 198#define OH_HUKS_KEY_BYTES(keySize) (((keySize) + 7) / 8) 199static OH_Huks_Result HksEncryptLoopUpdate(const struct OH_Huks_Blob *handle, const struct OH_Huks_ParamSet *paramSet, 200 const struct OH_Huks_Blob *inData, struct OH_Huks_Blob *outData) { 201 struct OH_Huks_Result ret; 202 ret.errorCode = OH_HUKS_SUCCESS; 203 struct OH_Huks_Blob inDataSeg = *inData; 204 uint8_t *lastPtr = inData->data + inData->size - 1; 205 struct OH_Huks_Blob outDataSeg = {MAX_OUTDATA_SIZE, NULL}; 206 uint8_t *cur = outData->data; 207 outData->size = 0; 208 inDataSeg.size = MAX_UPDATE_SIZE; 209 bool isFinished = false; 210 while (inDataSeg.data <= lastPtr) { 211 if (inDataSeg.data + MAX_UPDATE_SIZE <= lastPtr) { 212 outDataSeg.size = MAX_OUTDATA_SIZE; 213 } else { 214 isFinished = true; 215 inDataSeg.size = lastPtr - inDataSeg.data + 1; 216 break; 217 } 218 if (MallocAndCheckBlobData(&outDataSeg, outDataSeg.size).errorCode != (int32_t)OH_HUKS_SUCCESS) { 219 ret.errorCode = OH_HUKS_ERR_CODE_INTERNAL_ERROR; 220 return ret; 221 } 222 ret = OH_Huks_UpdateSession(handle, paramSet, &inDataSeg, &outDataSeg); 223 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 224 free(outDataSeg.data); 225 return ret; 226 } 227 std::copy(outDataSeg.data, outDataSeg.data + outDataSeg.size, cur); 228 cur += outDataSeg.size; 229 outData->size += outDataSeg.size; 230 free(outDataSeg.data); 231 if ((isFinished == false) && (inDataSeg.data + MAX_UPDATE_SIZE > lastPtr)) { 232 ret.errorCode = OH_HUKS_ERR_CODE_INTERNAL_ERROR; 233 return ret; 234 } 235 inDataSeg.data += MAX_UPDATE_SIZE; 236 } 237 struct OH_Huks_Blob outDataFinish = {inDataSeg.size * TIMES, NULL}; 238 if (MallocAndCheckBlobData(&outDataFinish, outDataFinish.size).errorCode != (int32_t)OH_HUKS_SUCCESS) { 239 ret.errorCode = OH_HUKS_ERR_CODE_INTERNAL_ERROR; 240 return ret; 241 } 242 ret = OH_Huks_FinishSession(handle, paramSet, &inDataSeg, &outDataFinish); 243 if (ret.errorCode != OH_HUKS_SUCCESS) { 244 free(outDataFinish.data); 245 return ret; 246 } 247 std::copy(outDataFinish.data, outDataFinish.data + outDataFinish.size, cur); 248 outData->size += outDataFinish.size; 249 free(outDataFinish.data); 250 return ret; 251} 252OH_Huks_Result HuksEncrypt(const struct OH_Huks_Blob *key, const struct OH_Huks_ParamSet *paramSet, 253 const struct OH_Huks_Blob *plainText, struct OH_Huks_Blob *cipherText) { 254 uint8_t handle[sizeof(uint64_t)] = {0}; 255 struct OH_Huks_Blob handleBlob = {sizeof(uint64_t), handle}; 256 OH_Huks_Result ret = OH_Huks_InitSession(key, paramSet, &handleBlob, nullptr); 257 if (ret.errorCode != OH_HUKS_SUCCESS) { 258 return ret; 259 } 260 ret = HksEncryptLoopUpdate(&handleBlob, paramSet, plainText, cipherText); 261 return ret; 262} 263static OH_Huks_Result BuildWrappedKeyData(struct OH_Huks_Blob **blobArray, uint32_t size, 264 struct OH_Huks_Blob *outData) { 265 uint32_t totalLength = size * sizeof(uint32_t); 266 struct OH_Huks_Result ret; 267 ret.errorCode = OH_HUKS_SUCCESS; 268 /* Data size. */ 269 for (uint32_t i = 0; i < size; ++i) { 270 totalLength += blobArray[i]->size; 271 } 272 struct OH_Huks_Blob outBlob = {0, nullptr}; 273 outBlob.size = totalLength; 274 ret = MallocAndCheckBlobData(&outBlob, outBlob.size); 275 if (ret.errorCode != OH_HUKS_SUCCESS) { 276 return ret; 277 } 278 uint32_t offset = 0; 279 /* Copy data. */ 280 for (uint32_t i = 0; i < size; ++i) { 281 if (totalLength - offset >= sizeof(blobArray[i]->size)) { 282 std::copy(reinterpret_cast<uint8_t *>(&blobArray[i]->size), 283 reinterpret_cast<uint8_t *>(&blobArray[i]->size) + sizeof(blobArray[i]->size), 284 outBlob.data + offset); 285 } else { 286 ret.errorCode = OH_HUKS_ERR_CODE_INTERNAL_ERROR; 287 return ret; 288 } 289 offset += sizeof(blobArray[i]->size); 290 if (totalLength - offset >= blobArray[i]->size) { 291 std::copy(blobArray[i]->data, blobArray[i]->data + blobArray[i]->size, outBlob.data + offset); 292 } else { 293 ret.errorCode = OH_HUKS_ERR_CODE_INTERNAL_ERROR; 294 return ret; 295 } 296 offset += blobArray[i]->size; 297 } 298 outData->size = outBlob.size; 299 outData->data = outBlob.data; 300 return ret; 301} 302static OH_Huks_Result CheckParamsValid(const struct HksImportWrappedKeyTestParams *params) { 303 struct OH_Huks_Result ret; 304 ret.errorCode = OH_HUKS_SUCCESS; 305 if (params == nullptr) { 306 ret.errorCode = OH_HUKS_ERR_CODE_ILLEGAL_ARGUMENT; 307 return ret; 308 } 309 if (params->wrappingKeyAlias == nullptr || params->genWrappingKeyParamSet == nullptr || 310 params->callerKeyAlias == nullptr || params->genCallerKeyParamSet == nullptr || 311 params->callerKekAlias == nullptr || params->callerKek == nullptr || 312 params->importCallerKekParamSet == nullptr || params->callerAgreeKeyAlias == nullptr || 313 params->agreeParamSet == nullptr || params->importWrappedKeyParamSet == nullptr || 314 params->importedKeyAlias == nullptr || params->importedPlainKey == nullptr) { 315 ret.errorCode = OH_HUKS_ERR_CODE_ILLEGAL_ARGUMENT; 316 return ret; 317 } 318 return ret; 319} 320static OH_Huks_Result GenerateAndExportHuksPublicKey(const struct HksImportWrappedKeyTestParams *params, 321 struct OH_Huks_Blob *huksPublicKey) { 322 OH_Huks_Result ret = OH_Huks_GenerateKeyItem(params->wrappingKeyAlias, params->genWrappingKeyParamSet, nullptr); 323 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 324 return ret; 325 } 326 huksPublicKey->size = params->publicKeySize; 327 ret = MallocAndCheckBlobData(huksPublicKey, huksPublicKey->size); 328 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 329 return ret; 330 } 331 ret = OH_Huks_ExportPublicKeyItem(params->wrappingKeyAlias, nullptr, huksPublicKey); 332 return ret; 333} 334static OH_Huks_Result GenerateAndExportCallerPublicKey(const struct HksImportWrappedKeyTestParams *params, 335 struct OH_Huks_Blob *callerSelfPublicKey) { 336 OH_Huks_Result ret = OH_Huks_GenerateKeyItem(params->callerKeyAlias, params->genCallerKeyParamSet, nullptr); 337 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 338 return ret; 339 } 340 callerSelfPublicKey->size = params->publicKeySize; 341 ret = MallocAndCheckBlobData(callerSelfPublicKey, callerSelfPublicKey->size); 342 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 343 return ret; 344 } 345 ret = OH_Huks_ExportPublicKeyItem(params->callerKeyAlias, params->genWrappingKeyParamSet, callerSelfPublicKey); 346 return ret; 347} 348static OH_Huks_Result ImportKekAndAgreeSharedSecret(const struct HksImportWrappedKeyTestParams *params, 349 const struct OH_Huks_Blob *huksPublicKey, 350 struct OH_Huks_Blob *outSharedKey) { 351 OH_Huks_Result ret = 352 OH_Huks_ImportKeyItem(params->callerKekAlias, params->importCallerKekParamSet, params->callerKek); 353 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 354 return ret; 355 } 356 ret = MallocAndCheckBlobData(outSharedKey, outSharedKey->size); 357 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 358 return ret; 359 } 360 ret = HuksAgreeKey(params->agreeParamSet, params->callerKeyAlias, huksPublicKey, outSharedKey); 361 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 362 return ret; 363 } 364 struct OH_Huks_ParamSet *importAgreeKeyParams = nullptr; 365 ret = InitParamSet(&importAgreeKeyParams, g_importAgreeKeyParams, 366 sizeof(g_importAgreeKeyParams) / sizeof(OH_Huks_Param)); 367 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 368 return ret; 369 } 370 ret = OH_Huks_ImportKeyItem(params->callerAgreeKeyAlias, importAgreeKeyParams, outSharedKey); 371 OH_Huks_FreeParamSet(&importAgreeKeyParams); 372 return ret; 373} 374static OH_Huks_Result EncryptImportedPlainKeyAndKek(const struct HksImportWrappedKeyTestParams *params, 375 struct OH_Huks_Blob *plainCipherText, 376 struct OH_Huks_Blob *kekCipherText) { 377 struct OH_Huks_ParamSet *encryptParamSet = nullptr; 378 OH_Huks_Result ret = 379 InitParamSet(&encryptParamSet, g_aesKekEncryptParams, sizeof(g_aesKekEncryptParams) / sizeof(OH_Huks_Param)); 380 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 381 return ret; 382 } 383 ret = HuksEncrypt(params->callerKekAlias, encryptParamSet, params->importedPlainKey, plainCipherText); 384 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 385 return ret; 386 } 387 ret = HuksEncrypt(params->callerAgreeKeyAlias, encryptParamSet, params->callerKek, kekCipherText); 388 OH_Huks_FreeParamSet(&encryptParamSet); 389 return ret; 390} 391static OH_Huks_Result ImportWrappedKey(const struct HksImportWrappedKeyTestParams *params, 392 struct OH_Huks_Blob *plainCipher, struct OH_Huks_Blob *kekCipherText, 393 struct OH_Huks_Blob *peerPublicKey, struct OH_Huks_Blob *wrappedKeyData) { 394 struct OH_Huks_Blob commonAad = {.size = AAD_SIZE, .data = reinterpret_cast<uint8_t *>(AAD)}; 395 struct OH_Huks_Blob commonNonce = {.size = NONCE_SIZE, .data = reinterpret_cast<uint8_t *>(NONCE)}; 396 struct OH_Huks_Blob keyMaterialLen = {.size = sizeof(uint32_t), .data = (uint8_t *)¶ms->keyMaterialLen}; 397 /* Copy the AEAD tag from the ciphertext and reduce its size. */ 398 const uint32_t tagSize = AEAD_TAG_SIZE; 399 uint8_t kekTagBuf[tagSize] = {0}; 400 struct OH_Huks_Blob kekTag = {.size = tagSize, .data = kekTagBuf}; 401 std::copy(plainCipher->data + (plainCipher->size - tagSize), 402 plainCipher->data + (plainCipher->size - tagSize) + tagSize, kekTag.data); 403 plainCipher->size -= tagSize; 404 /* Copy the AEAD tag from kekCipherText and reduce the tag size. */ 405 uint8_t agreeKeyTagBuf[tagSize] = {0}; 406 struct OH_Huks_Blob agreeKeyTag = {.size = tagSize, .data = agreeKeyTagBuf}; 407 std::copy(kekCipherText->data + (kekCipherText->size - tagSize), 408 kekCipherText->data + (kekCipherText->size - tagSize) + tagSize, agreeKeyTagBuf); 409 kekCipherText->size -= tagSize; 410 struct OH_Huks_Blob *blobArray[] = {peerPublicKey, &commonAad, &commonNonce, &agreeKeyTag, kekCipherText, 411 &commonAad, &commonNonce, &kekTag, &keyMaterialLen, plainCipher}; 412 OH_Huks_Result ret = BuildWrappedKeyData(blobArray, OH_HUKS_IMPORT_WRAPPED_KEY_TOTAL_BLOBS, wrappedKeyData); 413 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 414 return ret; 415 } 416 struct OH_Huks_Param *purpose = nullptr; 417 ret = OH_Huks_GetParam(params->importWrappedKeyParamSet, OH_HUKS_TAG_PURPOSE, &purpose); 418 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 419 return ret; 420 } 421 ret = OH_Huks_ImportWrappedKeyItem(params->importedKeyAlias, params->wrappingKeyAlias, 422 params->importWrappedKeyParamSet, wrappedKeyData); 423 return ret; 424} 425OH_Huks_Result HksImportWrappedKeyTestCommonCase(const struct HksImportWrappedKeyTestParams *params) { 426 OH_Huks_Result ret = CheckParamsValid(params); 427 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 428 return ret; 429 } 430 struct OH_Huks_Blob huksPublicKey = {0, nullptr}; 431 struct OH_Huks_Blob callerSelfPublicKey = {0, nullptr}; 432 struct OH_Huks_Blob outSharedKey = {.size = OH_HUKS_KEY_BYTES(OH_HUKS_AES_KEY_SIZE_256), .data = nullptr}; 433 struct OH_Huks_Blob wrappedKeyData = {0, nullptr}; 434 uint8_t plainKeyCipherBuffer[OH_HUKS_MAX_KEY_SIZE] = {0}; 435 struct OH_Huks_Blob plainCipherText = {OH_HUKS_MAX_KEY_SIZE, plainKeyCipherBuffer}; 436 uint8_t kekCipherTextBuffer[OH_HUKS_MAX_KEY_SIZE] = {0}; 437 struct OH_Huks_Blob kekCipherText = {OH_HUKS_MAX_KEY_SIZE, kekCipherTextBuffer}; 438 /* Simulate the encrypted key import scenario. Import a key from device A (remote device) to device B (local device). */ 439 do { 440 /** 441 * 1. If the key to be imported from device A is an asymmetric key pair, convert it into the HUKS key material format **To_Import_Key**. Skip over this step if the key is a symmetric key. 442 * This example uses a 256-bit AES key (symmetric key) as an example. 443 */ 444 /* 2. Generate an asymmetric key pair Wrapping_Key (public key Wrapping_Pk and private key Wrapping_Sk) with the purpose of HUKS_KEY_PURPOSE_UNWRAP for device B, export the public key Wrapping_Pk of Wrapping_Key, and save it to huksPubKey. 445 */ 446 ret = GenerateAndExportHuksPublicKey(params, &huksPublicKey); 447 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 448 break; 449 } 450 /* 3. Use the same algorithm to generate an asymmetric key pair Caller_Key (public key Caller_Pk and private key Caller_Sk) with the purpose of HUKS_KEY_PURPOSE_UNWRAP for device A, export the public key Caller_Pk of Caller_Key, save it to callerSelfPublicKey. 451 */ 452 ret = GenerateAndExportCallerPublicKey(params, &callerSelfPublicKey); 453 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 454 break; 455 } 456 /** 457 4. Generate a symmetric key Caller_Kek for device A. This key is used to encrypt To_Import_Key. 458 * 5. Perform key agreement with the private key **Caller_Sk** in **Caller_Key** of device A and the public key **Wrapping_Pk** in **Wrapping_Key** of device B to yield a **Shared_Key**. 459 */ 460 ret = ImportKekAndAgreeSharedSecret(params, &huksPublicKey, &outSharedKey); 461 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 462 break; 463 } 464 /** 465 * 6. Use Caller_Kek to encrypt To_Import_Key of device A and generate To_Import_Key_Enc. 466 * 7. Use Shared_Key to encrypt Caller_Kek of device A and generate Caller_Kek_Enc. 467 */ 468 ret = EncryptImportedPlainKeyAndKek(params, &plainCipherText, &kekCipherText); 469 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 470 break; 471 } 472 /* 8. Encapsulate the key material Caller_Pk, To_Import_Key_Enc, and Caller_Kek_Enc of device A, and sends it to device B. 473 * In this example, Caller_Pk is placed in callerSelfPublicKey, To_Import_Key_Enc in PlainKeyEncData, and Caller_Kek_Enc in KekEncData. 474 * 9. Import the encapsulated key material to device B. 475 */ 476 ret = ImportWrappedKey(params, &plainCipherText, &kekCipherText, &callerSelfPublicKey, &wrappedKeyData); 477 } while (0); 478 /* 10. Delete the intermediate keys (keys used for encrypting the key to import) from devices A and B. */ 479 HUKS_FREE_BLOB(huksPublicKey); 480 HUKS_FREE_BLOB(callerSelfPublicKey); 481 HUKS_FREE_BLOB(outSharedKey); 482 HUKS_FREE_BLOB(wrappedKeyData); 483 return ret; 484} 485void HksClearKeysForWrappedKeyTest(const struct HksImportWrappedKeyTestParams *params) { 486 OH_Huks_Result ret = CheckParamsValid(params); 487 if (ret.errorCode != (int32_t)OH_HUKS_SUCCESS) { 488 return; 489 } 490 (void)OH_Huks_DeleteKeyItem(params->wrappingKeyAlias, nullptr); 491 (void)OH_Huks_DeleteKeyItem(params->callerKeyAlias, nullptr); 492 (void)OH_Huks_DeleteKeyItem(params->callerKekAlias, nullptr); 493 (void)OH_Huks_DeleteKeyItem(params->callerAgreeKeyAlias, nullptr); 494 (void)OH_Huks_DeleteKeyItem(params->importedKeyAlias, nullptr); 495} 496static OH_Huks_Result InitCommonTestParamsAndDoImport(struct HksImportWrappedKeyTestParams *importWrappedKeyTestParams, 497 const struct OH_Huks_Param *importedKeyParamSetArray, 498 uint32_t arraySize) { 499 struct OH_Huks_ParamSet *genX25519KeyParamSet = nullptr; 500 struct OH_Huks_ParamSet *genCallerKeyParamSet = nullptr; 501 struct OH_Huks_ParamSet *callerImportParamsKek = nullptr; 502 struct OH_Huks_ParamSet *agreeParamSet = nullptr; 503 struct OH_Huks_ParamSet *importPlainKeyParams = nullptr; 504 OH_Huks_Result ret; 505 do { 506 ret = InitParamSet(&genX25519KeyParamSet, g_genWrappingKeyParams, 507 sizeof(g_genWrappingKeyParams) / sizeof(OH_Huks_Param)); 508 if (ret.errorCode != OH_HUKS_SUCCESS) { 509 break; 510 } 511 importWrappedKeyTestParams->genWrappingKeyParamSet = genX25519KeyParamSet; 512 importWrappedKeyTestParams->publicKeySize = g_x25519PubKeySize; 513 ret = InitParamSet(&genCallerKeyParamSet, g_genCallerX25519Params, 514 sizeof(g_genCallerX25519Params) / sizeof(OH_Huks_Param)); 515 if (ret.errorCode != OH_HUKS_SUCCESS) { 516 break; 517 } 518 importWrappedKeyTestParams->genCallerKeyParamSet = genCallerKeyParamSet; 519 ret = InitParamSet(&callerImportParamsKek, g_importParamsCallerKek, 520 sizeof(g_importParamsCallerKek) / sizeof(OH_Huks_Param)); 521 if (ret.errorCode != OH_HUKS_SUCCESS) { 522 break; 523 } 524 importWrappedKeyTestParams->importCallerKekParamSet = callerImportParamsKek; 525 ret = InitParamSet(&agreeParamSet, g_callerAgreeParams, sizeof(g_callerAgreeParams) / sizeof(OH_Huks_Param)); 526 if (ret.errorCode != OH_HUKS_SUCCESS) { 527 break; 528 } 529 importWrappedKeyTestParams->agreeParamSet = agreeParamSet; 530 ret = InitParamSet(&importPlainKeyParams, importedKeyParamSetArray, arraySize); 531 if (ret.errorCode != OH_HUKS_SUCCESS) { 532 break; 533 } 534 importWrappedKeyTestParams->importWrappedKeyParamSet = importPlainKeyParams; 535 ret = HksImportWrappedKeyTestCommonCase(importWrappedKeyTestParams); 536 } while (0); 537 OH_Huks_FreeParamSet(&genX25519KeyParamSet); 538 OH_Huks_FreeParamSet(&genCallerKeyParamSet); 539 OH_Huks_FreeParamSet(&callerImportParamsKek); 540 OH_Huks_FreeParamSet(&agreeParamSet); 541 OH_Huks_FreeParamSet(&importPlainKeyParams); 542 return ret; 543} 544static napi_value ImportWrappedKey(napi_env env, napi_callback_info info) { 545 struct HksImportWrappedKeyTestParams importWrappedKeyTestParams001 = {0}; 546 importWrappedKeyTestParams001.wrappingKeyAlias = &g_wrappingKeyAliasAes256; 547 importWrappedKeyTestParams001.keyMaterialLen = g_importedAes256PlainKey.size; 548 importWrappedKeyTestParams001.callerKeyAlias = &g_callerKeyAliasAes256; 549 importWrappedKeyTestParams001.callerKekAlias = &g_callerKekAliasAes256; 550 importWrappedKeyTestParams001.callerKek = &g_callerAes256Kek; 551 importWrappedKeyTestParams001.callerAgreeKeyAlias = &g_callerAgreeKeyAliasAes256; 552 importWrappedKeyTestParams001.importedKeyAlias = &g_importedKeyAliasAes256; 553 importWrappedKeyTestParams001.importedPlainKey = &g_importedAes256PlainKey; 554 OH_Huks_Result ohResult = 555 InitCommonTestParamsAndDoImport(&importWrappedKeyTestParams001, g_importWrappedAes256Params, 556 sizeof(g_importWrappedAes256Params) / sizeof(struct OH_Huks_Param)); 557 HksClearKeysForWrappedKeyTest(&importWrappedKeyTestParams001); 558 napi_value ret; 559 napi_create_int32(env, ohResult.errorCode, &ret); 560 return ret; 561} 562``` 563 564 565## Verification 566 567Use [OH_Huks_IsKeyItemExist](../../reference/apis-universal-keystore-kit/_huks_key_api.md#oh_huks_iskeyitemexist) to check whether the key exists. If the key exists, the key is successfully imported. 568 569```c++ 570#include "huks/native_huks_api.h" 571#include "huks/native_huks_param.h" 572#include <string.h> 573static napi_value IsKeyExist(napi_env env, napi_callback_info info) 574{ 575 /* 1. Set the key alias. */ 576 struct OH_Huks_Blob keyAlias = { 577 (uint32_t)strlen("test_key"), 578 (uint8_t *)"test_key" 579 }; 580 581 /* 2. Call OH_Huks_IsKeyItemExist to check whether the key exists. */ 582 struct OH_Huks_Result ohResult = OH_Huks_IsKeyItemExist(&keyAlias, NULL); 583 if (ohResult.errorCode != OH_HUKS_SUCCESS) { 584 // Operation failed. 585 } else { 586 // Operation successful. 587 } 588} 589``` 590