HarmonyOS 鸿蒙Next 请提供下huks密钥协商DH算法的案例

发布于 1周前 作者 nodeper 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 请提供下huks密钥协商DH算法的案例

需要huks与java服务端进行密钥协商,DH安全性更高,请提供一下具体的代码案例

2 回复

对于密钥类型可以在创建时选择cryptoFramework.createAsyKeyGeneratorBySpec(‘DH’)即可,具体的相关文档,请参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework-0000001820881417#ZH-CN_TOPIC_0000001857916905__cryptoframeworkcreateasykeygeneratorbyspec10 具体相关步骤:

1.使用cryptoFramework.createAsyKeyGeneratorBySpec(‘DH’)来生成密钥对

2.使用cryptoFramework.createCipher来创建cipher对象,进行加解密

3.使用cipher.doFinal()来进行加解密

目前可供参考的案例链接如下:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/huks-key-agreement-arkts-0000001774280386,DH协商密钥可以类比案例中的密钥类型X25519 256,且密钥仅在HUKS内使用为例,完成密钥协商。

具体的场景介绍及支持的算法规格,请参考密钥生成支持的算法:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/huks-key-generation-overview-0000001821000309#ZH-CN_TOPIC_0000001857876121__支持的算法

参考

import huks from '@ohos.security.huks';

@Entry

@Component

struct Huks_DH2048_01 {

@State signValue: string = '';

build() {

Row() {

Column() {

Button('generateKeypair')

.margin(10)

.width(150)

.onClick(async () => {

HuksDhAgreeTest()

})

}.width('100%')

}.height('100%')

}

}

// 工具函数,将大端16进制数组数据转换为大整数

function Uint8ArrayToBigInt(arr: Uint8Array): bigint {

let i = 0;

const byteMax: bigint = BigInt("0x100")

let result: bigint = BigInt("0")

while (i < arr.length) {

result = result * byteMax

result = result + BigInt(arr[i])

i += 1;

}

return result;

}

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);

}

const aliasAlice = 'alice'

const aliasBob = 'bob'

const dh2048Agree: Array<huks.HuksParam> = [{

tag: huks.HuksTag.HUKS_TAG_ALGORITHM,

value: huks.HuksKeyAlg.HUKS_ALG_DH,

}, {

tag: huks.HuksTag.HUKS_TAG_PURPOSE,

value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE,

}, {

tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,

value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048,

}]

const dhGenOptions: huks.HuksOptions = {

properties: dh2048Agree,

inData: new Uint8Array([])

}

const emptyOptions: huks.HuksOptions = {

properties: [],

inData: new Uint8Array([])

}


async function HuksDhAgreeExportTest(pubKeyAlice: huks.HuksReturnResult, pubKeyBob: huks.HuksReturnResult) {

/* 三段式 */

const handleAlice = await huks.initSession(aliasAlice, dhGenOptions)

const dhAgreeUpdateBobPubKey: huks.HuksOptions = {

properties: [

...dh2048Agree, {

tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,

value: huks.HuksKeyStorageType.HUKS_STORAGE_KEY_EXPORT_ALLOWED

}],

inData: pubKeyBob.outData

}

await huks.updateSession(handleAlice.handle, dhAgreeUpdateBobPubKey)

const agreedKeyFromAlice = await huks.finishSession(handleAlice.handle, emptyOptions)

console.log(`finish session ok! agreedKeyFromAlice export is 0x${Uint8ArrayToBigInt(agreedKeyFromAlice.outData).toString(16)}`)

const handleBob = await huks.initSession(aliasBob, dhGenOptions)

const dhAgreeUpdateAlicePubKey: huks.HuksOptions = {

properties: [

...dh2048Agree, {

tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,

value: huks.HuksKeyStorageType.HUKS_STORAGE_KEY_EXPORT_ALLOWED

}],

inData: pubKeyAlice.outData

}

await huks.updateSession(handleBob.handle, dhAgreeUpdateAlicePubKey)

const agreedKeyFromBob = await huks.finishSession(handleBob.handle, emptyOptions)

console.log(`finish session ok! agreedKeyFromBob export is 0x${Uint8ArrayToBigInt(agreedKeyFromBob.outData).toString(16)}`)

}

async function HuksDhAgreeInHuksTest(pubKeyAlice: huks.HuksReturnResult, pubKeyBob: huks.HuksReturnResult) {

const dhAgree: Array<huks.HuksParam> = [{

tag: huks.HuksTag.HUKS_TAG_ALGORITHM,

value: huks.HuksKeyAlg.HUKS_ALG_DH,

}, {

tag: huks.HuksTag.HUKS_TAG_PURPOSE,

value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE,

}]

const dhAgreeInit: huks.HuksOptions = {

properties: [

...dhAgree, {

tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,

value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,

}, {

tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS

}, {

tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,

value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS

}],

inData: new Uint8Array([])

}

const dhAgreeFinishParams: Array<huks.HuksParam> = [

{ tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS },

{

tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,

value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS

},

{ tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, value: true },

{ tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES },

{ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 },

{

tag: huks.HuksTag.HUKS_TAG_PURPOSE,

value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT

},

]
const handleAlice = await huks.initSession(aliasAlice, dhAgreeInit)

const dhAgreeUpdateBobPubKey: huks.HuksOptions = {

properties: [

...dhAgree, {

tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS

}, {

tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,

value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS

}],

inData: pubKeyBob.outData

}

await huks.updateSession(handleAlice.handle, dhAgreeUpdateBobPubKey)

const aliasAgreedKeyFromAlice = 'agreedKeyFromAlice'

const dhAgreeAliceFinish: huks.HuksOptions = {

properties: [

...dhAgreeFinishParams, {

tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,

value: StringToUint8Array(aliasAgreedKeyFromAlice)

}],

inData: new Uint8Array([])

}

const agreedKeyFromAlice = await huks.finishSession(handleAlice.handle, dhAgreeAliceFinish)

console.log(`finish session ok! agreedKeyFromAlice in huks is 0x${Uint8ArrayToBigInt(agreedKeyFromAlice.outData)

.toString(16)}`)

const aliceAgreedExist = await huks.isKeyItemExist(aliasAgreedKeyFromAlice, emptyOptions)

console.log(`isKeyItemExist agreedKeyFromAlice in huks is ${aliceAgreedExist}`)

const handleBob = await huks.initSession(aliasBob, dhAgreeInit)

const dhAgreeUpdateAlicePubKey: huks.HuksOptions = {

properties: [

...dhAgree, {

tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS

}, {

tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,

value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS

}],

inData: pubKeyAlice.outData

}

const aliasAgreedKeyFromBob = 'agreedKeyFromBob'

await huks.updateSession(handleBob.handle, dhAgreeUpdateAlicePubKey)

const dhAgreeBobFinish: huks.HuksOptions = {

properties: [

...dhAgreeFinishParams, {

tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,

value: StringToUint8Array(aliasAgreedKeyFromBob)

}],

inData: new Uint8Array([])

}

const agreedKeyFromBob = await huks.finishSession(handleBob.handle, dhAgreeBobFinish)

console.log(`finish session ok! agreedKeyFromBob in huks is 0x${Uint8ArrayToBigInt(agreedKeyFromBob.outData)

.toString(16)}`)

const bobAgreedExist = await huks.isKeyItemExist(aliasAgreedKeyFromBob, emptyOptions)

console.log(`isKeyItemExist agreedKeyFromBob in huks is ${bobAgreedExist}`)

await huks.deleteKeyItem(aliasAgreedKeyFromAlice, emptyOptions)

await huks.deleteKeyItem(aliasAgreedKeyFromBob, emptyOptions)

}

export default async function HuksDhAgreeTest() {

/* 生成A、B密钥 */

await huks.generateKeyItem(aliasAlice, dhGenOptions)

await huks.generateKeyItem(aliasBob, dhGenOptions)

/* 导出A、B密钥中的公钥 */

const pubKeyAlice = await huks.exportKeyItem(aliasAlice, emptyOptions)

const pubKeyBob = await huks.exportKeyItem(aliasBob, emptyOptions)

console.log(`begin HuksDhAgreeExportTest!`)

await HuksDhAgreeExportTest(pubKeyAlice, pubKeyBob)

console.log(`begin HuksDhAgreeInHuksTest!`)

await HuksDhAgreeInHuksTest(pubKeyAlice, pubKeyBob)

console.log(`end HuksDhAgreeTest!`)

await huks.deleteKeyItem(aliasAlice, emptyOptions)

await huks.deleteKeyItem(aliasBob, emptyOptions)

}

更多关于HarmonyOS 鸿蒙Next 请提供下huks密钥协商DH算法的案例的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


对于HarmonyOS 鸿蒙Next系统中的huks密钥协商算法有所了解。但关于DH(Diffie-Hellman)算法的案例,由于DH算法在计算效率上相对较低,尤其是在处理大素数时计算复杂度较高,而且其安全性基于离散对数问题,随着计算能力的提升可能会受到一定影响,因此在现代系统中,它逐渐被更高效和安全的算法如ECDH(Elliptic Curve Diffie-Hellman)所取代。

HarmonyOS 鸿蒙Next系统更倾向于使用ECDH算法进行密钥协商,该算法基于椭圆曲线密码学原理,提供高强度安全性的同时,计算效率也相对较高,尤其适用于资源受限的设备,如移动设备和物联网设备。

不过,尽管DH算法在HarmonyOS中的直接应用案例较少,但我可以提供一个ECDH算法的案例以供参考:

在HarmonyOS中,ECDH算法的使用通常涉及通信双方在椭圆曲线上选择各自的私钥,通过一系列复杂的椭圆曲线点运算,结合对方的公钥,共同计算出一个共享密钥。这一过程可以通过Crypto Architecture Kit等框架服务实现。

如果确实需要了解DH算法的详细案例,建议查阅HarmonyOS的官方文档或相关开发资料。

回到顶部