1.RASproperties
import huks from '@ohos.security.huks';
function GetRSA4096GenerateProperties(): Array<huks.HuksParam> {
return [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
}, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_4096
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}, {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
}, {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
}]
}
function GetRSA4096EncryptProperties(): Array<huks.HuksParam> {
return [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
}, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_4096
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}, {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
}, {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
}]
}
function GetRSA4096DecryptProperties(): Array<huks.HuksParam> {
return [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
}, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_4096
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}, {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
}, {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
}]
}
export {
GetRSA4096GenerateProperties,
GetRSA4096EncryptProperties,
GetRSA4096DecryptProperties
}
2.ED25519
import huks from '@ohos.security.huks';
function GetEd25519GenerateProperties(): Array<huks.HuksParam> {
return [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ED25519
}, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
}]
}
function GetEd25519SignProperties(): Array<huks.HuksParam> {
return [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ED25519,
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN
}, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256,
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_NONE,
}]
}
function GetEd25519VerifyProperties(): Array<huks.HuksParam> {
return [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ED25519,
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
}, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256,
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_NONE,
}]
}
export {
GetEd25519GenerateProperties,
GetEd25519SignProperties,
GetEd25519VerifyProperties as Ed25519TestProperties
}
dh
import { huks } from '@kit.UniversalKeystoreKit'
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 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
}
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 dh2048Agree: Array<huks.HuksParam> = [
...dhAgree, {
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 HuksDhAgreeExportKey(keyAlias: string, peerPubKey: huks.HuksReturnResult): Promise<huks.HuksReturnResult> {
const initHandle = await huks.initSession(keyAlias, 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: peerPubKey.outData
}
await huks.updateSession(initHandle.handle, dhAgreeUpdateBobPubKey)
return await huks.finishSession(initHandle.handle, emptyOptions)
}
async function HuksDhAgreeExportTest(
aliasA: string, aliasB: string,
pubKeyA: huks.HuksReturnResult, pubKeyB: huks.HuksReturnResult) {
const agreedKeyFromAlice = await HuksDhAgreeExportKey(aliasA, pubKeyB)
console.log(`ok! agreedKeyFromAlice export is 0x${Uint8ArrayToBigInt(agreedKeyFromAlice.outData).toString(16)}`)
const agreedKeyFromBob = await HuksDhAgreeExportKey(aliasB, pubKeyA)
console.log(`ok! agreedKeyFromBob export is 0x${Uint8ArrayToBigInt(agreedKeyFromBob.outData).toString(16)}`)
}
async function HuksDhAgreeInHuks(keyAlias: string, peerPubKey: huks.HuksReturnResult, aliasAgreedKey: string): Promise<huks.HuksReturnResult> {
const onlyUsedInHuks: 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,
}]
const dhAgreeInit: huks.HuksOptions = {
properties: [
...dhAgree,
{ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, },
...onlyUsedInHuks],
inData: new Uint8Array([])
}
const dhAgreeFinishParams: Array<huks.HuksParam> = [
...onlyUsedInHuks,
{ 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 handle = await huks.initSession(keyAlias, dhAgreeInit)
const dhAgreeUpdatePubKey: huks.HuksOptions = {
properties: [...dhAgree, ...onlyUsedInHuks],
inData: peerPubKey.outData
}
await huks.updateSession(handle.handle, dhAgreeUpdatePubKey)
const dhAgreeAliceFinnish: huks.HuksOptions = {
properties: [...dhAgreeFinishParams, {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, value: StringToUint8Array(aliasAgreedKey)
}], inData: new Uint8Array([])
}
return await huks.finishSession(handle.handle, dhAgreeAliceFinnish)
}
async function HuksDhAgreeInHuksTest(
aliasA: string, aliasB: string,
pubKeyA: huks.HuksReturnResult, pubKeyB: huks.HuksReturnResult,
aliasAgreedKeyFromA: string, aliasAgreedKeyFromB: string) {
const finishAliceResult = await HuksDhAgreeInHuks(aliasA, pubKeyB, aliasAgreedKeyFromA)
console.log(`ok! finishAliceResult in huks is 0x${Uint8ArrayToBigInt(finishAliceResult.outData).toString(16)}`)
const aliceAgreedExist = await huks.isKeyItemExist(aliasAgreedKeyFromA, emptyOptions)
console.log(`ok! aliceAgreedExist in huks is ${aliceAgreedExist}`)
const finishBobResult = await HuksDhAgreeInHuks(aliasB, pubKeyA, aliasAgreedKeyFromB)
console.log(`ok! finishBobResult in huks is 0x${Uint8ArrayToBigInt(finishBobResult.outData).toString(16)}`)
const bobAgreedExist = await huks.isKeyItemExist(aliasAgreedKeyFromB, emptyOptions)
console.log(`ok! bobAgreedExist in huks is ${bobAgreedExist}`)
await huks.deleteKeyItem(aliasAgreedKeyFromA, emptyOptions)
await huks.deleteKeyItem(aliasAgreedKeyFromB, emptyOptions)
}
export default async function HuksDhAgreeTest() {
const aliasAlice = 'alice'
const aliasBob = 'bob'
await huks.generateKeyItem(aliasAlice, dhGenOptions)
await huks.generateKeyItem(aliasBob, dhGenOptions)
const pubKeyAlice = await huks.exportKeyItem(aliasAlice, emptyOptions)
const pubKeyBob = await huks.exportKeyItem(aliasBob, emptyOptions)
await HuksDhAgreeExportTest(aliasAlice, aliasBob, pubKeyAlice, pubKeyBob)
await HuksDhAgreeInHuksTest(aliasAlice, aliasBob, pubKeyAlice, pubKeyBob, 'agreedKeyFromAlice', 'agreedKeyFromBob')
await huks.deleteKeyItem(aliasAlice, emptyOptions)
await huks.deleteKeyItem(aliasBob, emptyOptions)
}
java
package org.example;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
public class generateAesKey {
private static byte[] iv="0011223344556677".getBytes();
private static String text="Hello, world!";
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidCipherTextException {
String[] tmp = bytesToHex(iv);
for (String b : tmp) {
System.out.print("0x"+b+",");
}
// Add the Bouncy Castle provider
Security.addProvider(new BouncyCastleProvider());
// 创建keyGenerate对象,BC指的是Bouncy Castle
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES", "BC");
//设置密钥长度
keyGenerator.init(256);
SecretKey secretKey = keyGenerator.generateKey();
//生成密钥
byte[] key = secretKey.getEncoded();
//打印密钥
System.out.println("AES密钥: " + key);
//将byte[]转化为16进制数组
String[] hexArray = bytesToHex(key);
//打印16进制数组
for (String hex : hexArray) {
System.out.print("0x"+hex + ",");
}
//创建AES加密引擎
BlockCipher engine=new AESEngine();
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
cipher.init(true,new ParametersWithIV(new KeyParameter(key),iv));
//进行加密
int outputSize = cipher.getOutputSize(text.getBytes().length);
byte[] output = new byte[outputSize];
//计算偏移量
int offset=cipher.processBytes(text.getBytes(),0,text.getBytes().length,output,0);
cipher.doFinal(output,offset);
//打印加密后的数据
System.out.println("");
String[] ans = bytesToHex(output);
for (String hex : ans) {
System.out.print("0x"+hex + ",");
}
}
//将byte[]转化为16进制数组
private static String[] bytesToHex(byte[] key) {
String[] hexArray = new String[key.length];
for (int i = 0; i < key.length; i++) {
hexArray[i] = Integer.toHexString(key[i] & 0xFF);
}
return hexArray;
}
}
https://gitee.com/gao-gaoyang/BestDemoForHuks
标签:TAG,huks,HuksTag,tag,value,算法,HUKS,密钥,测试
From: https://www.cnblogs.com/zwkyd/p/18310311