HarmonyOS 加密导入RSA1024秘钥对Demo

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

非对称密钥加密导入请参考以下demo示例:

非对称密钥加密导入请参考以下demo示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';

let IV = '0000000000000000';
let AAD = "abababababababab";
let NONCE = "hahahahahaha";
let TAG_SIZE = 16;
let FILED_LENGTH = 4;

let rsa2048KeyPairMaterial = new Uint8Array([
  0x01, 0x00, 0x00, 0x00, // 密钥算法:huks.HuksKeyAlg.HUKS_ALG_RSA = 1
  0x00, 0x08, 0x00, 0x00, // 密钥大小(比特):2048
  0x00, 0x01, 0x00, 0x00, // 模数n长度(字节):256
  0x03, 0x00, 0x00, 0x00, // 公钥指数e长度(字节):3
  0x00, 0x01, 0x00, 0x00, // 私钥指数d长度(字节):256
  // 模数n
  0xc5, 0x35, 0x62, 0x48, 0xc4, 0x92, 0x87, 0x73, 0x0d, 0x42, 0x96, 0xfc, 0x7b, 0x11, 0x05, 0x06,
  0x0f, 0x8d, 0x66, 0xc1, 0x0e, 0xad, 0x37, 0x44, 0x92, 0x95, 0x2f, 0x6a, 0x55, 0xba, 0xec, 0x1d,
  0x54, 0x62, 0x0a, 0x4b, 0xd3, 0xc7, 0x05, 0xe4, 0x07, 0x40, 0xd9, 0xb7, 0xc2, 0x12, 0xcb, 0x9a,
  0x90, 0xad, 0xe3, 0x24, 0xe8, 0x5e, 0xa6, 0xf8, 0xd0, 0x6e, 0xbc, 0xd1, 0x69, 0x7f, 0x6b, 0xe4,
  0x2b, 0x4e, 0x1a, 0x65, 0xbb, 0x73, 0x88, 0x6b, 0x7c, 0xaf, 0x7e, 0xd0, 0x47, 0x26, 0xeb, 0xa5,
  0xbe, 0xd6, 0xe8, 0xee, 0x9c, 0xa5, 0x66, 0xa5, 0xc9, 0xd3, 0x25, 0x13, 0xc4, 0x0e, 0x6c, 0xab,
  0x50, 0xb6, 0x50, 0xc9, 0xce,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, 0x0d, 0x08, 0x12, 0xf3, 0x26,
  0xf8, 0x5e, 0xeb, 0x10, 0x27, 0xae, 0xaa, 0xc3, 0xad, 0x6c, 0xc1, 0x89, 0xdb, 0x7d, 0x5a, 0x12,
  0x55, 0xad, 0x11, 0x19, 0xa1, 0xa9, 0x8f, 0x0b, 0x6d, 0x78, 0x8d, 0x1c, 0xdf, 0xe5, 0x63, 0x82,
  0x0b, 0x7d, 0x23, 0x04, 0xb4, 0x75, 0x8c, 0xed, 0x77, 0xfc, 0x1a, 0x85, 0x29, 0x11, 0xe0, 0x61,
]);

let callerAes256Kek = "The is kek to encrypt rsa2048key";
let callerKeyAlias = "test_caller_key_ecdh_aes192";
let callerKekAliasAes256 = "test_caller_kek_ecdh_aes256";
let callerAgreeKeyAliasAes256 = "test_caller_agree_key_ecdh_aes256";
let importedKeyAliasRsa2048 = "test_import_key_ecdh_rsa2048";
let huksPubKey: Uint8Array;
let callerSelfPublicKey: Uint8Array;
let outSharedKey: Uint8Array;
let outPlainKeyEncData: Uint8Array;
let outKekEncData: Uint8Array;
let outKekEncTag: Uint8Array;
let outAgreeKeyEncTag: Uint8Array;
let mask = [0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000];

function subUint8ArrayOf(arrayBuf: Uint8Array, start: number, end: number) {
  let arr: number[] = [];
  for (let i = start; i < end && i < arrayBuf.length; ++i) {
    arr.push(arrayBuf[i]);
  }
  return new Uint8Array(arr);
}
function stringToUint8Array(str: string) {
  let arr: number[] = [];
  for (let i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
  return new Uint8Array(arr);
}
function assignLength(length: number, arrayBuf: Uint8Array, startIndex: number) {
  let index = startIndex;
  for (let i = 0; i < 4; i++) {
    arrayBuf[index++] = (length & mask[i]) >> (i * 8);
  }
  return 4;
}
function assignData(data: Uint8Array, arrayBuf: Uint8Array, startIndex: number) {
  let index = startIndex;
  for (let i = 0; i < data.length; i++) {
    arrayBuf[index++] = data[i];
  }
  return data.length;
}

let genWrappingKeyParams: huks.HuksOptions = {
  properties: new Array<huks.HuksParam>(
    {
      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
      value: huks.HuksKeyAlg.HUKS_ALG_ECC
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
    },
    {
      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
      value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PADDING,
      value: huks.HuksKeyPadding.HUKS_PADDING_NONE
    }
  )
}
let genCallerEcdhParams:huks.HuksOptions = {
  properties: new Array<huks.HuksParam>(
    {
      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
      value: huks.HuksKeyAlg.HUKS_ALG_ECC
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
    },
    {
      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
      value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256
    }
  )
}
let importParamsCallerKek: huks.HuksOptions = {
  properties: new Array<huks.HuksParam>(
    {
      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
      value: huks.HuksKeyAlg.HUKS_ALG_AES
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    },
    {
      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
      value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PADDING,
      value: huks.HuksKeyPadding.HUKS_PADDING_NONE
    },
    {
      tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
      value: huks.HuksCipherMode.HUKS_MODE_GCM
    },
    {
      tag: huks.HuksTag.HUKS_TAG_DIGEST,
      value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
    },
    {
      tag: huks.HuksTag.HUKS_TAG_IV,
      value: stringToUint8Array(IV)
    }
  ),
  inData: stringToUint8Array(callerAes256Kek)
}

let importParamsAgreeKey: huks.HuksOptions = {
  properties: new Array<huks.HuksParam>(
    {
      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
      value: huks.HuksKeyAlg.HUKS_ALG_AES
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    },
    {
      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
      value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PADDING,
      value: huks.HuksKeyPadding.HUKS_PADDING_NONE
    },
    {
      tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
      value: huks.HuksCipherMode.HUKS_MODE_GCM
    },
    {
      tag: huks.HuksTag.HUKS_TAG_DIGEST,
      value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
    },
    {
      tag: huks.HuksTag.HUKS_TAG_IV,
      value: stringToUint8Array(IV)
    }
  ),
}
let callerAgreeParams: huks.HuksOptions = {
  properties: new Array<huks.HuksParam>(
    {
      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
      value: huks.HuksKeyAlg.HUKS_ALG_ECDH
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
    },
    {
      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
      value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256
    }
  )
}
let encryptKeyCommonParams: huks.HuksOptions = {
  properties: new Array<huks.HuksParam>(
    {
      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
      value: huks.HuksKeyAlg.HUKS_ALG_AES
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    },
    {
      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
      value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PADDING,
      value: huks.HuksKeyPadding.HUKS_PADDING_NONE
    },
    {
      tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
      value: huks.HuksCipherMode.HUKS_MODE_GCM
    },
    {
      tag: huks.HuksTag.HUKS_TAG_NONCE,
      value: stringToUint8Array(NONCE)
    },
    {
      tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
      value: stringToUint8Array(AAD)
    }
  ),
}
let importWrappedRsa2048Params: huks.HuksOptions = {
  properties: new Array<huks.HuksParam>(
    {
      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
      value: huks.HuksKeyAlg.HUKS_ALG_RSA
    },
    {
      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    },
    {
      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
      value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
    },
    {
      tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
      value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
    }
  )
}

async function publicGenerateItemFunc(keyAlias: string, huksOptions: huks.HuksOptions) {
  console.info(`enter promise generateKeyItem`);
  try {
    await huks.generateKeyItem(keyAlias, huksOptions)
      .then(data => {
        console.info(`promise: generateKeyItem success, data = ${JSON.stringify(data)}`);
      })
      .catch((err: BusinessError) => {
        console.error(`promise: generateKeyItem failed` + err);

      })
  } catch (err) {
    console.error(`promise: generateKeyItem invalid` + err);

  }
}
async function publicImportKeyItemFunc(keyAlias: string, HuksOptions: huks.HuksOptions) {
  console.info(`enter promise importKeyItem`);
  try {
    await huks.importKeyItem(keyAlias, HuksOptions)
      .then(data => {
        console.info(`promise: importKeyItem success, data = ${JSON.stringify(data)}`);
      }).catch((err: BusinessError) => {
        console.error(`promise: importKeyItem failed` + err);

      })
  } catch (err) {
    console.error(`promise: importKeyItem input arg invalid` + err);

  }
}
async function publicDeleteKeyItemFunc(KeyAlias: string, HuksOptions: huks.HuksOptions) {
  console.info(`enter promise deleteKeyItem`);
  try {
    await huks.deleteKeyItem(KeyAlias, HuksOptions)
      .then(data => {
        console.info(`promise: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
      })
      .catch((err: BusinessError) => {
        console.error(`promise: deleteKeyItem failed` + err);

      })
  } catch (err) {
    console.error(`promise: deleteKeyItem input arg invalid` + err);

  }
}
function importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, huksOptions: huks.HuksOptions) {
  return new Promise<void>((resolve, reject) => {
    try {
      huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, (error, data) => {
        if (error) {
          reject(error);
        } else {
          resolve(data);
        }
      });
    } catch (error) {

    }
  });
}
async function publicImportWrappedKeyFunc(keyAlias: string, wrappingKeyAlias: string, huksOptions: huks.HuksOptions) {
  console.info(`enter promise importWrappedKeyItem`);
  for (let i = 0; i < huksOptions.inData!.length; i++) {
    console.error(`${i}: ${huksOptions.inData![i]}`);
  }
  try {
    await importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions)
      .then((data) => {
        console.info(`promise: importWrappedKeyItem success, data = ${JSON.stringify(data)}`);
      })
      .catch((error: BusinessError) => {
        console.error(`promise: importWrappedKeyItem failed` + error);

      });
  } catch (error) {
    console.error(`promise: importWrappedKeyItem input arg invalid` + error);

  }
}
async function publicImportWrappedKeyPromise(keyAlias: string, wrappingKeyAlias: string, huksOptions: huks.HuksOptions) {
  console.info(`enter promise importWrappedKeyItem`);
  try {
    await huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions)
      .then((data) => {
        console.info(`promise: importWrappedKeyItem success, data = ${JSON.stringify(data)}`);
      })
      .catch((error: BusinessError) => {
        console.error(`promise: importWrappedKeyItem failed` + error);

      });
  } catch (error) {
    console.error(`promise: importWrappedKeyItem input arg invalid` + error);

  }
}

async function publicInitFunc(srcKeyAlias: string, HuksOptions: huks.HuksOptions) {
  let handle: number = 0;
  console.info(`enter promise doInit`);
  try {
    await huks.initSession(srcKeyAlias, HuksOptions)
      .then((data) => {
        console.info(`promise: doInit success, data = ${JSON.stringify(data)}`);
        handle = data.handle;
      })
      .catch((error: BusinessError) => {
        console.error(`promise: doInit key failed` + error);

      });
  } catch (error) {
    console.error(`promise: doInit input arg invalid` + error);

  }
  return handle;
}
async function publicUpdateSessionFunction(handle: number, HuksOptions: huks.HuksOptions) {
  const maxUpdateSize = 64;
  const inData = HuksOptions.inData!;
  const lastInDataPosition = inData.length - 1;
  let inDataSegSize = maxUpdateSize;
  let inDataSegPosition = 0;
  let isFinished = false;
  let outData: number[] = [];

  while (inDataSegPosition <= lastInDataPosition) {
    if (inDataSegPosition + maxUpdateSize > lastInDataPosition) {
      isFinished = true;
      inDataSegSize = lastInDataPosition - inDataSegPosition + 1;
      console.info(`enter promise doUpdate`);
      HuksOptions.inData = new Uint8Array(
        Array.from(inData).slice(inDataSegPosition, inDataSegPosition + inDataSegSize)
      );
      break;
    }
    HuksOptions.inData = new Uint8Array(
      Array.from(inData).slice(inDataSegPosition, inDataSegPosition + inDataSegSize)
    );
    console.info(`enter promise doUpdate`);
    try {
      await huks.updateSession(handle, HuksOptions)
        .then((data) => {
          console.error(`promise: doUpdate success, data = ${JSON.stringify(data)}`);
          outData = outData.concat(Array.from(data.outData!));
        })
        .catch((error: BusinessError) => {
          console.error(`promise: doUpdate failed` + error);

        });
    } catch (error) {
      console.error(`promise: doUpdate input arg invalid` + error);

    }
    if ((!isFinished) && (inDataSegPosition + maxUpdateSize > lastInDataPosition)) {
      console.log(`update size invalid isFinished = ${isFinished}`);
      console.log(`inDataSegPosition = ${inDataSegPosition}`);
      console.log(`lastInDataPosition = ${lastInDataPosition}`);

      return;
    }
    inDataSegPosition += maxUpdateSize;
  }
  return outData;
}
async function publicFinishSession(handle: number, HuksOptions: huks.HuksOptions, inData: number[]) {
  let outData: number[] = [];
  console.info(`enter promise doFinish`);
  try {
    await huks.finishSession(handle, HuksOptions)
      .then((data) => {
        console.info(`promise: doFinish success, data = ${JSON.stringify(data)}`);
        outData = inData.concat(Array.from(data.outData!));
      })
      .catch((error: BusinessError) => {
        console.error(`promise: doFinish key failed` + error);

      });
  } catch (error) {
    console.error(`promise: doFinish input arg invalid` + error);

  }
  return new Uint8Array(outData);
}
async function cipherFunction(keyAlias: string, HuksOptions: huks.HuksOptions) {
  let handle = await publicInitFunc(keyAlias, HuksOptions);
  let tmpData = await publicUpdateSessionFunction(handle, HuksOptions);
  let outData = await publicFinishSession(handle, HuksOptions, tmpData!);
  return outData;
}
async function agreeFunction(keyAlias: string, HuksOptions: huks.HuksOptions, huksPublicKey: Uint8Array) {
  let handle = await publicInitFunc(keyAlias, HuksOptions);
  let outSharedKey: Uint8Array = new Uint8Array;
  HuksOptions.inData = huksPublicKey;
  console.info(`enter promise doUpdate`);
  try {
    await huks.updateSession(handle, HuksOptions)
      .then((data) => {
        console.error(`promise: doUpdate success, data = ${JSON.stringify(data)}`);
      })
      .catch((error: BusinessError) => {
        console.error(`promise: doUpdate failed` + error);

      });
  } catch (error) {
    console.error(`promise: doUpdate input arg invalid` + error);

  }
  console.info(`enter promise doInit`);
  try {
    await huks.finishSession(handle, HuksOptions)
      .then((data) => {
        console.info(`promise: doInit success, data = ${JSON.stringify(data)}`);
        outSharedKey = data.outData as Uint8Array;
      })
      .catch((error: BusinessError) => {
        console.error(`promise: doInit key failed` + error);

      });
  } catch (error) {
    console.error(`promise: doInit input arg invalid` + error);

  }
  return outSharedKey;
}
async function ImportKekAndAgreeSharedSecret(callerKekAlias: string, importKekParams: huks.HuksOptions, callerKeyAlias: string, huksPublicKey: Uint8Array, agreeParams: huks.HuksOptions) {
  await publicImportKeyItemFunc(callerKekAlias, importKekParams);
  outSharedKey = await agreeFunction(callerKeyAlias, agreeParams, huksPublicKey);
  importParamsAgreeKey.inData = outSharedKey;
  await publicImportKeyItemFunc(callerAgreeKeyAliasAes256, importParamsAgreeKey);
}
async function generateAndExportPublicKey(keyAlias: string, HuksOptions: huks.HuksOptions, caller: Boolean) {
  await publicGenerateItemFunc(keyAlias, HuksOptions);
  try {
    await huks.exportKeyItem(keyAlias, HuksOptions)
      .then((data) => {
        console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`);
        if (caller) {
          callerSelfPublicKey = data.outData as Uint8Array;
        } else {
          huksPubKey = data.outData as Uint8Array;
        }
      })
      .catch((error: BusinessError) => {
        console.error(`promise: exportKeyItem failed` + error);

      });
  } catch (error) {
    console.error(`promise: generate pubKey failed` + error);

  }
}
async function EncryptImportedPlainKeyAndKek() {
  encryptKeyCommonParams.inData = rsa2048KeyPairMaterial;
  let plainKeyEncData = await cipherFunction(callerKekAliasAes256, encryptKeyCommonParams);
  outKekEncTag = subUint8ArrayOf(plainKeyEncData, plainKeyEncData.length - TAG_SIZE, plainKeyEncData.length)
  outPlainKeyEncData = subUint8ArrayOf(plainKeyEncData, 0, plainKeyEncData.length - TAG_SIZE)
  encryptKeyCommonParams.inData = stringToUint8Array(callerAes256Kek)
  let kekEncData = await cipherFunction(callerAgreeKeyAliasAes256, encryptKeyCommonParams)
  outAgreeKeyEncTag = subUint8ArrayOf(kekEncData, kekEncData.length - TAG_SIZE, kekEncData.length)
  outKekEncData = subUint8ArrayOf(kekEncData, 0, kekEncData.length - TAG_SIZE)
}

async function BuildWrappedDataAndImportWrappedKey() {
  let plainKeySizeBuff = new Uint8Array(4);
  assignLength(rsa2048KeyPairMaterial.length, plainKeySizeBuff, 0);
  let wrappedData = new Uint8Array(
    FILED_LENGTH + huksPubKey.length +
      FILED_LENGTH + AAD.length +
      FILED_LENGTH + NONCE.length +
      FILED_LENGTH + TAG_SIZE +
      FILED_LENGTH + outKekEncData.length +
      FILED_LENGTH + AAD.length +
      FILED_LENGTH + NONCE.length +
      FILED_LENGTH + TAG_SIZE +
      FILED_LENGTH + plainKeySizeBuff.length +
      FILED_LENGTH + outPlainKeyEncData.length
  );
  let index = 0;
  let AADUint8Array = stringToUint8Array(AAD);
  let NonceArray = stringToUint8Array(NONCE);
  index += assignLength(callerSelfPublicKey.length, wrappedData, index); // 4
  index += assignData(callerSelfPublicKey, wrappedData, index); // 91
  index += assignLength(AADUint8Array.length, wrappedData, index); // 4
  index += assignData(AADUint8Array, wrappedData, index); // 16
  index += assignLength(NonceArray.length, wrappedData, index); // 4
  index += assignData(NonceArray, wrappedData, index); // 12
  index += assignLength(outAgreeKeyEncTag.length, wrappedData, index); // 4
  index += assignData(outAgreeKeyEncTag, wrappedData, index); // 16
  index += assignLength(outKekEncData.length, wrappedData, index); // 4
  index += assignData(outKekEncData, wrappedData, index); // 32
  index += assignLength(AADUint8Array.length, wrappedData, index); // 4
  index += assignData(AADUint8Array, wrappedData, index); // 16
  index += assignLength(NonceArray.length, wrappedData, index); // 4
  index += assignData(NonceArray, wrappedData, index); // 12
  index += assignLength(outKekEncTag.length, wrappedData, index); // 4
  index += assignData(outKekEncTag, wrappedData, index); // 16
  index += assignLength(plainKeySizeBuff.length, wrappedData, index); // 4
  index += assignData(plainKeySizeBuff, wrappedData, index); // 4
  index += assignLength(outPlainKeyEncData.length, wrappedData, index); // 4
  index += assignData(outPlainKeyEncData, wrappedData, index); // 24
  return wrappedData;
}
export class ImportRSA2048Demo {
  /* 模拟加密导入密钥场景,设备A为远端设备(导入设备),设备B为本端设备(被导入设备) */
  async ImportWrappedKey() {
    /**
     * 1.设备A将待导入密钥转换成HUKS密钥材料格式To_Import_Key(仅针对非对称密钥,若待导入密钥是对称密钥则可省略此步骤),
     * 本示例使用rsa2048KeyPairMaterial(非对称密钥)作为模拟
     */

    /* 2.设备B生成一个加密导入用途的、用于协商的非对称密钥对Wrapping_Key(公钥Wrapping_Pk,私钥Wrapping_Sk),其密钥用途设置为unwrap,导出Wrapping_Key公钥Wrapping_Pk存放在变量huksPubKey中 */
    const srcKeyAliesWrap = 'HUKS_Basic_Capability_Import_0200';
    await generateAndExportPublicKey(srcKeyAliesWrap, genWrappingKeyParams, false);

    /* 3.设备A使用和设备B同样的算法,生成一个加密导入用途的、用于协商的非对称密钥对Caller_Key(公钥Caller_Pk,私钥Caller_Sk),导出Caller_Key公钥Caller_Pk存放在变量callerSelfPublicKey中 */
    await generateAndExportPublicKey(callerKeyAlias, genCallerEcdhParams, true);

    /**
     * 4.设备A生成一个对称密钥Caller_Kek,该密钥后续将用于加密To_Import_Key
     * 5.设备A基于Caller_Key的私钥Caller_Sk和Wrapping_Key的公钥Wrapping_Pk,协商出Shared_Key
     */
    await ImportKekAndAgreeSharedSecret(callerKekAliasAes256, importParamsCallerKek, callerKeyAlias, huksPubKey, callerAgreeParams);

    /**
     * 6.设备A使用Caller_Kek加密To_Import_Key,生成To_Import_Key_Enc
     * 7.设备A使用Shared_Key加密Caller_Kek,生成Caller_Kek_Enc
     */
    await EncryptImportedPlainKeyAndKek();

    /* 8.设备A封装Caller_Pk、To_Import_Key_Enc、Caller_Kek_Enc等加密导入的材料并发送给设备B。本示例作为变量存放在callerSelfPublicKey,PlainKeyEncData,KekEncData */
    let wrappedData = await BuildWrappedDataAndImportWrappedKey();
    importWrappedRsa2048Params.inData = wrappedData;

    /* 9.设备B导入封装的加密密钥材料 */
    await publicImportWrappedKeyFunc(importedKeyAliasRsa2048, srcKeyAliesWrap, importWrappedRsa2048Params);

    /* 10.设备A、B删除用于加密导入的密钥 */
    await publicDeleteKeyItemFunc(srcKeyAliesWrap, genWrappingKeyParams);
    await publicDeleteKeyItemFunc(callerKeyAlias, genCallerEcdhParams);
    await publicDeleteKeyItemFunc(importedKeyAliasRsa2048, importWrappedRsa2048Params);
    await publicDeleteKeyItemFunc(callerKekAliasAes256, callerAgreeParams);
  }
}

最后调用

import { ImportRSA2048Demo } from './ImportRSA2048Demo';
const TAG: string = '[HUKS]'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button() {
          Text('加密导入rsa2048公钥')
            .fontSize(20)
            .fontWeight(FontWeight.Bold)
        }.onClick((event: ClickEvent) => {
          let rsa2048: ImportRSA2048Demo = new ImportRSA2048Demo()
          rsa2048.ImportWrappedKey();
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

要用huks的加密导入密钥功能,密钥格式需要满足huks密钥材料要求,原提供的导入demo中有拼接导入密钥材料的代码,请对照导入demo修改您的代码,密钥格式请参考:

https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/UniversalKeystoreKit/huks-concepts.md#%E5%AF%86%E9%92%A5%E6%9D%90%E6%96%99%E6%A0%BC%E5%BC%8F

分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS RSA加密的base64转换
20浏览 • 1回复 待解决
HarmonyOS RSA私钥加密解密
44浏览 • 1回复 待解决
如何使用RSA加密明文数据
496浏览 • 1回复 待解决
HarmonyOS 使用crypto进行交换
58浏览 • 1回复 待解决
如何实现RSA的公PK加密一段文字
638浏览 • 1回复 待解决
HarmonyOS RSA解密
16浏览 • 1回复 待解决
HarmonyOS RSA加密方式
672浏览 • 1回复 待解决
HarmonyOS RSA如何用公解密
666浏览 • 0回复 待解决
HarmonyOS rsa加密报错
40浏览 • 1回复 待解决
HarmonyOS RSA分段加密乱码
628浏览 • 1回复 待解决
HarmonyOS 实现RSA加密功能
621浏览 • 1回复 待解决
HarmonyOS 指定私钥生成SM2的方法
22浏览 • 1回复 待解决
RSA导入外部密钥实现加解密
813浏览 • 1回复 待解决
HarmonyOS RSA加密失败问题
35浏览 • 1回复 待解决
HarmonyOS RSA加密算法实现
36浏览 • 1回复 待解决