在线观看www成人影院-在线观看www日本免费网站-在线观看www视频-在线观看操-欧美18在线-欧美1级

0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

鴻蒙開發:Universal Keystore Kit 密鑰管理服務 加密導入密鑰 ArkTS

jf_46214456 ? 來源:jf_46214456 ? 作者:jf_46214456 ? 2024-07-08 14:22 ? 次閱讀

加密導入密鑰(ArkTS)

以加密導入ECDH密鑰對為例,涉及業務側加密密鑰的[密鑰生成]、[協商])等操作不在本示例中體現。

開發步驟

  1. 設備A(導入設備)將待導入密鑰轉換成[HUKS密鑰材料格式]To_Import_Key(僅針對非對稱密鑰,若待導入密鑰是對稱密鑰則可省略此步驟)。
  2. 設備B(被導入設備)生成一個加密導入用途的、用于協商的非對稱密鑰對Wrapping_Key(公鑰Wrapping_Pk,私鑰Wrapping_Sk),其密鑰用途設置為unwrap,導出Wrapping_Key的公鑰材料Wrapping_Pk并保存。
  3. 設備A使用和設備B同樣的算法,生成一個加密導入用途的、用于協商的非對稱密鑰對Caller_Key(公鑰Caller_Pk,私鑰Caller_Sk),導出Caller_Key的公鑰材料Caller_Pk并保存。
  4. 設備A生成一個對稱密鑰Caller_Kek,該密鑰后續將用于加密To_Import_Key。
  5. 設備A基于Caller_Key的私鑰Caller_Sk和設備B Wrapping_Key的公鑰Wrapping_Pk,協商出Shared_Key。
  6. 設備A使用Caller_Kek加密To_Import_Key,生成To_Import_Key_Enc。
  7. 設備A使用Shared_Key加密Caller_Kek,生成Caller_Kek_Enc。
  8. 設備A封裝Caller_Pk、Caller_Kek_Enc、To_Import_Key_Enc等加密導入的密鑰材料并發送給設備B,加密導入密鑰材料格式見[加密導入密鑰材料格式]。
  9. 設備B導入封裝的加密密鑰材料。
  10. 設備A、B刪除用于加密導入的密鑰。
  11. 開發前請熟悉鴻蒙開發指導文檔 :[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md]
import { huks } from "@kit.UniversalKeystoreKit";
let IV = '0000000000000000';
let AAD = "abababababababab";
let NONCE = "hahahahahaha";
let TAG_SIZE = 16;
let FILED_LENGTH = 4;
let importedAes192PlainKey = "The aes192 key to import";
let callerAes256Kek = "The is kek to encrypt aes192 key";
let callerKeyAlias = "test_caller_key_ecdh_aes192";
let callerKekAliasAes256 = "test_caller_kek_ecdh_aes256";
let callerAgreeKeyAliasAes256 = "test_caller_agree_key_ecdh_aes256";
let importedKeyAliasAes192 = "test_import_key_ecdh_aes192";
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 importWrappedAes192Params: 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 |
            huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
        },
        {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_192
        },
        {
            tag: huks.HuksTag.HUKS_TAG_PADDING,
            value: huks.HuksKeyPadding.HUKS_PADDING_NONE
        },
        {
            tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
            value: huks.HuksCipherMode.HUKS_MODE_CBC
        },
        {
            tag: huks.HuksTag.HUKS_TAG_DIGEST,
            value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
        },
        {
            tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
            value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
        },
        {
            tag: huks.HuksTag.HUKS_TAG_IV,
            value: stringToUint8Array(IV)
        }
    )
}
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: Error) = > {
            console.error(`promise: generateKeyItem failed, ${JSON.stringify(err)}`);
        })
    } catch (err) {
        console.error(`promise: generateKeyItem invalid, ${JSON.stringify(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: Error) = > {
            console.error(`promise: importKeyItem failed, ${JSON.stringify(err)}`);
        })
    } catch (err) {
        console.error(`promise: importKeyItem input arg invalid, ${JSON.stringify(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: Error) = > {
            console.error(`promise: deleteKeyItem failed, ${JSON.stringify(err)}`);
        })
    } catch (err) {
        console.error(`promise: deleteKeyItem input arg invalid, ${JSON.stringify(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: Error) = > {
            console.error(`promise: importWrappedKeyItem failed, ${JSON.stringify(error)}`);
        });
    } catch (error) {
        console.error(`promise: importWrappedKeyItem input arg invalid, ${JSON.stringify(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: Error) = > {
            console.error(`promise: importWrappedKeyItem failed, ${JSON.stringify(error)}`);
        });
    } catch (error) {
        console.error(`promise: importWrappedKeyItem input arg invalid, ${JSON.stringify(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: Error) = > {
            console.error(`promise: doInit key failed, ${JSON.stringify(error)}`);
        });
    } catch (error) {
        console.error(`promise: doInit input arg invalid, ${JSON.stringify(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`);
            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.info(`promise: doUpdate success, data = ${JSON.stringify(data)}`);
                outData = outData.concat(Array.from(data.outData!));
            })
            .catch((error: Error) = > {
                console.error(`promise: doUpdate failed, ${JSON.stringify(error)}`);
            });
        } catch (error) {
            console.error(`promise: doUpdate input arg invalid, ${JSON.stringify(error)}`);
        }
        if ((!isFinished) && (inDataSegPosition + maxUpdateSize > lastInDataPosition)) {
            console.error(`update size invalid isFinished = ${isFinished}`);
            console.error(`inDataSegPosition = ${inDataSegPosition}`);
            console.error(`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: Error) = > {
            console.error(`promise: doFinish key failed, ${JSON.stringify(error)}`);
        });
    } catch (error) {
        console.error(`promise: doFinish input arg invalid, ${JSON.stringify(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: Error) = > {
            console.error(`promise: doUpdate failed, ${JSON.stringify(error)}`);
        });
    } catch (error) {
        console.error(`promise: doUpdate input arg invalid, ${JSON.stringify(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: Error) = > {
            console.error(`promise: doInit key failed, ${JSON.stringify(error)}`);
        });
    } catch (error) {
        console.error(`promise: doInit input arg invalid, ${JSON.stringify(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: Error) = > {
            console.error(`promise: exportKeyItem failed, ${JSON.stringify(error)}`);
        });
    } catch (error) {
        console.error(`promise: generate pubKey failed, ${JSON.stringify(error)}`);
    }
}
async function EncryptImportedPlainKeyAndKek(keyAlias: string) {
    encryptKeyCommonParams.inData = stringToUint8Array(keyAlias)
    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(plainKey: string) {
    let plainKeySizeBuff = new Uint8Array(4);
    assignLength(plainKey.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;
}
/* 模擬加密導入密鑰場景,設備A為遠端設備(導入設備),設備B為本端設備(被導入設備) */
async function ImportWrappedKey() {
    /**
     * 1.設備A將待導入密鑰轉換成HUKS密鑰材料格式To_Import_Key(僅針對非對稱密鑰,若待導入密鑰是對稱密鑰則可省略此步驟),
     *   本示例使用importedAes256PlainKey(對稱密鑰)作為模擬
     */

    /* 2.設備B生成一個加密導入用途的、用于協商的非對稱密鑰對Wrapping_Key(公鑰Wrapping_Pk,私鑰Wrapping_Sk),其密鑰用途設置為unwrap,導出Wrapping_Key公鑰Wrapping_Pk存放在變量huksPubKey中 */
    const srcKeyAliasWrap = 'HUKS_Basic_Capability_Import_0200';
    await generateAndExportPublicKey(srcKeyAliasWrap, 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(importedAes192PlainKey);

    /* 8.設備A封裝Caller_Pk、To_Import_Key_Enc、Caller_Kek_Enc等加密導入的材料并發送給設備B。本示例作為變量存放在callerSelfPublicKey,PlainKeyEncData,KekEncData */
    let wrappedData = await BuildWrappedDataAndImportWrappedKey(importedAes192PlainKey);
    importWrappedAes192Params.inData = wrappedData;

    /* 9.設備B導入封裝的加密密鑰材料 */
    await publicImportWrappedKeyFunc(importedKeyAliasAes192, srcKeyAliasWrap, importWrappedAes192Params);

    /* 10.設備A、B刪除用于加密導入的密鑰 */
    await publicDeleteKeyItemFunc(srcKeyAliasWrap, genWrappingKeyParams);
    await publicDeleteKeyItemFunc(callerKeyAlias, genCallerEcdhParams);
    await publicDeleteKeyItemFunc(importedKeyAliasAes192, importWrappedAes192Params);
    await publicDeleteKeyItemFunc(callerKekAliasAes256, callerAgreeParams);
}

調測驗證

調用[huks.isKeyItemExist]驗證密鑰是否存在,如密鑰存在即表示密鑰導入成功。

QQ截圖20240705210937.png

`HarmonyOSOpenHarmony鴻蒙文檔籽料:mau123789是v直接拿`

import { huks } from "@kit.UniversalKeystoreKit";
/*
 * 確定密鑰別名和封裝密鑰屬性參數集
 */
let keyAlias = 'test_import_key_ecdh_aes192';
let isKeyExist:Boolean;
let keyProperties: Array< huks.HuksParam > = [{
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_AES,
}];
let huksOptions:huks.HuksOptions = {
    properties: keyProperties, // 非空填充
    inData: new Uint8Array(new Array()) // 非空填充
}
try {
    huks.isKeyItemExist(keyAlias, huksOptions, (error, data)= > {
        if (error) {
            console.error(`callback: isKeyItemExist failed, ${JSON.stringify(error)}`);
        } else {
            if (data !== null && data.valueOf() !== null) {
                isKeyExist = data.valueOf();
                console.info(`callback: isKeyItemExist success, isKeyExist = ${isKeyExist}`);
            }
        }
    });
} catch (error) {
    console.error(`callback: isKeyItemExist input arg invalid, ${JSON.stringify(error)}`);
}

審核編輯 黃宇

聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • 密鑰
    +關注

    關注

    1

    文章

    138

    瀏覽量

    19759
  • 鴻蒙
    +關注

    關注

    57

    文章

    2352

    瀏覽量

    42859
收藏 人收藏

    評論

    相關推薦

    鴻蒙開發Universal Keystore Kit密鑰管理服務簡介

    Universal Keystore Kit密鑰管理服務,下述簡稱為HUKS)向業務/應用提供
    的頭像 發表于 07-04 14:20 ?452次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b><b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b>簡介

    鴻蒙開發Universal Keystore Kit密鑰管理服務 生成密鑰ArkTS

    以生成DH密鑰為例,生成隨機密鑰。具體的場景介紹及支持的算法規格
    的頭像 發表于 07-05 15:17 ?326次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b><b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> 生成<b class='flag-5'>密鑰</b><b class='flag-5'>ArkTS</b>

    鴻蒙開發Universal Keystore Kit密鑰管理服務 密鑰導入介紹及算法規格

    如果業務在HUKS外部生成密鑰(比如應用間協商生成、服務器端生成),業務可以將密鑰導入到HUKS中由HUKS進行管理
    的頭像 發表于 07-06 10:45 ?683次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b><b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> <b class='flag-5'>密鑰</b><b class='flag-5'>導入</b>介紹及算法規格

    鴻蒙開發Universal Keystore Kit密鑰管理服務 明文導入密鑰 ArkTS

    分別以導入AES256與RSA2048密鑰為例,具體的場景介紹及支持的算法規格
    的頭像 發表于 07-08 10:22 ?384次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b><b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> 明文<b class='flag-5'>導入</b><b class='flag-5'>密鑰</b> <b class='flag-5'>ArkTS</b>

    鴻蒙開發Universal Keystore Kit密鑰管理服務 明文導入密鑰C、C++

    以明文導入ECC密鑰為例。具體的場景介紹及支持的算法規格
    的頭像 發表于 07-08 10:01 ?308次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b><b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> 明文<b class='flag-5'>導入</b><b class='flag-5'>密鑰</b>C、C++

    鴻蒙開發Universal Keystore Kit密鑰管理服務 加密導入密鑰C、C++

    加密導入ECDH密鑰對為例,涉及業務側加密密鑰的[密鑰生成]、[協商]等操作不在本示例中體現。
    的頭像 發表于 07-08 15:26 ?360次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b><b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> <b class='flag-5'>加密</b><b class='flag-5'>導入</b><b class='flag-5'>密鑰</b>C、C++

    鴻蒙開發Universal Keystore Kit 密鑰管理服務 密鑰使用介紹及通用流程

    為了實現對數據機密性、完整性等保護,可使用生成/導入密鑰,對數據進行密鑰操作
    的頭像 發表于 07-09 11:56 ?502次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b> <b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> <b class='flag-5'>密鑰</b>使用介紹及通用流程

    鴻蒙開發Universal Keystore Kit 密鑰管理服務 密鑰協商ArkTS

    以協商密鑰類型為X25519 256,并密鑰僅在HUKS內使用為例,完成密鑰協商。
    的頭像 發表于 07-10 09:22 ?333次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b> <b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> <b class='flag-5'>密鑰</b>協商<b class='flag-5'>ArkTS</b>

    鴻蒙開發Universal Keystore Kit 密鑰管理服務 密鑰協商 C、C++

    以協商密鑰類型為ECDH,并密鑰僅在HUKS內使用為例,完成密鑰協商。具體的場景介紹及支持的算法規格,請參考[密鑰生成支持的算法]。
    的頭像 發表于 07-10 14:27 ?358次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b> <b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> <b class='flag-5'>密鑰</b>協商 C、C++

    鴻蒙開發Universal Keystore Kit密鑰管理服務 密鑰派生C、C++

    以HKDF256密鑰為例,完成密鑰派生。具體的場景介紹及支持的算法規格,請參考[密鑰生成支持的算法]。
    的頭像 發表于 07-11 14:28 ?297次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b><b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> <b class='flag-5'>密鑰</b>派生C、C++

    鴻蒙開發Universal Keystore Kit 密鑰管理服務 HMAC ArkTS

    HMAC是密鑰相關的哈希運算消息認證碼(Hash-based Message Authentication Code),是一種基于Hash函數和密鑰進行消息認證的方法。
    的頭像 發表于 07-12 18:22 ?639次閱讀

    鴻蒙開發Universal Keystore Kit密鑰管理服務 密鑰刪除ArkTS

    為保證數據安全性,當不需要使用該密鑰時,應該刪除密鑰
    的頭像 發表于 07-12 14:56 ?299次閱讀

    鴻蒙開發Universal Keystore Kit 密鑰管理服務 獲取密鑰屬性ArkTS

    HUKS提供了接口供業務獲取指定密鑰的相關屬性。在獲取指定密鑰屬性前,需要確保已在HUKS中生成或導入持久化存儲的密鑰
    的頭像 發表于 07-17 10:46 ?312次閱讀

    鴻蒙開發Universal Keystore Kit 密鑰管理服務 獲取密鑰屬性C C++

    HUKS提供了接口供業務獲取指定密鑰的相關屬性。在獲取指定密鑰屬性前,需要確保已在HUKS中生成或導入持久化存儲的密鑰
    的頭像 發表于 07-17 09:47 ?366次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>:<b class='flag-5'>Universal</b> <b class='flag-5'>Keystore</b> <b class='flag-5'>Kit</b> <b class='flag-5'>密鑰</b><b class='flag-5'>管理</b><b class='flag-5'>服務</b> 獲取<b class='flag-5'>密鑰</b>屬性C C++

    鴻蒙開發Universal Keystore Kit 密鑰管理服務 查詢密鑰別名集 ArkTS

    HUKS提供了接口供應用查詢密鑰別名集。
    的頭像 發表于 07-18 09:34 ?357次閱讀
    主站蜘蛛池模板: 靓装爱神12丝袜在线播放| 国内在线观看精品免费视频| 国产无圣光高清一区二区| 天天插天天插天天插| 综合欧美一区二区三区| 天堂资源在线官网bt| 激情综合五月网| 免费国产不卡午夜福在线观看| 欧美日韩亚洲一区| 欧美伦理一区二区三区| 香蕉操| 一区二区三区四区视频在线 | 我想看三级特黄| 国产美女在线精品观看| 成人午夜大片免费视频77777| 亚洲免费三级| 国产床戏无遮掩视频播放| 94久久国产乱子伦精品免费| 性色成人网| 成人在线免费网站| 日本68xxxxxxxxx59| 日韩美a一级毛片| 天天做天天做天天综合网| 乱轮黄色小说| 激情综合网五月婷婷| 国产成人综合亚洲怡春院| 推倒都市极品贵妇| 一级视频在线观看免费| 午夜免费网址| 久久综合九色综合欧洲| 国产爱搞| 深爱五月激情五月| 午夜影视免费完整高清在线观看网站| 91av成人| 六月婷婷激情| a级午夜毛片免费一区二区| 色综合久久久久久久久五月| 天天干视频在线观看| 中国videos偷窥| bt天堂资源| 美女扒尿口给男人桶到爽|