This topic uses AES-128, RSA-2048, SM2, and DES64 as examples to describe the encryption and decryption workflows. For details about the scenarios and supported algorithms, see Supported Algorithms.
Key Generation
Specify the key alias. For details about the naming rules, see Key Generation Overview and Algorithm Specifications.
Initialize the key property set.
Use generateKeyItem to generate a key. For details, see Key Generation.
Alternatively, you can import a key.
Encryption
Obtain the key alias.
Obtain the data to be encrypted.
Use HuksParam to set encryption algorithm parameters.
The parameters to be configured vary with the algorithm used.
For details about the specifications, see Encryption and Decryption Overview and Algorithm Specifications.
Use initSession to initialize a key session. The session handle is returned after the initialization.
Use finishSession with the session handle to obtain the ciphertext.
Decryption
Obtain the key alias.
Obtain the ciphertext to be decrypted.
Use HuksParam to set decryption algorithm parameters.
The parameters to be configured vary with the algorithm used.
For details about the specifications, see Encryption and Decryption Overview and Algorithm Specifications.
Use initSession to initialize a key session. The session handle is returned after the initialization.
Use finishSession to obtain the data decrypted.
Key Deletion
Use deleteKeyItem to delete the key that is not required. For details, see Deleting a Key.
/*
* The following uses AES/CBC/PKCS7 with promise-based APIs.
*/
import { huks } from '@kit.UniversalKeystoreKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { BusinessError } from '@kit.BasicServicesKit';
let aesKeyAlias = 'test_aesKeyAlias';
let handle: number;
let plainText = '123456';
let IV = cryptoFramework.createRandom().generateRandomSync(12).data;
let cipherData: Uint8Array;
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 uint8ArrayToString(fileData: Uint8Array) {
return Array.from(fileData, byte => String.fromCharCode(byte)).join('');
}
function getAesGenerateProperties() {
let properties: huks.HuksParam[] = [{
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_128
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}];
return properties;
}
function getAesEncryptProperties() {
let properties: huks.HuksParam[] = [{
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_128
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
}, {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_CBC
}, {
tag: huks.HuksTag.HUKS_TAG_IV,
value: IV
}];
return properties;
}
function getAesDecryptProperties() {
let properties: huks.HuksParam[] = [{
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_128
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
}, {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_CBC
}, {
tag: huks.HuksTag.HUKS_TAG_IV,
value: IV
}];
return properties;
}
async function generateAesKey() {
/*
* Simulate the key generation scenario.
*/
/*
* 1. Obtain the parameters for key generation.
*/
let genProperties = getAesGenerateProperties();
let options: huks.HuksOptions = {
properties: genProperties
}
/*
* 2. Call generateKeyItem.
*/
await huks.generateKeyItem(aesKeyAlias, options)
.then(() => {
console.info(`promise: generate AES Key success`);
}).catch((error: BusinessError) => {
console.error(`promise: generate AES Key failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function encryptData() {
/*
* Simulate the encryption scenario.
*/
/*
* 1. Obtain the algorithm parameters for encryption.
*/
let encryptProperties = getAesEncryptProperties();
let options: huks.HuksOptions = {
properties: encryptProperties,
inData: stringToUint8Array(plainText)
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(aesKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init EncryptData failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the ciphertext.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: encrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
cipherData = data.outData as Uint8Array;
}).catch((error: BusinessError) => {
console.error(`promise: encrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function decryptData() {
/*
* Simulate the decryption scenario.
* 1. Obtain the key alias.
*/
/*
* 1. Obtain the algorithm parameters for decryption.
*/
let decryptOptions = getAesDecryptProperties()
let options: huks.HuksOptions = {
properties: decryptOptions,
inData: cipherData
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(aesKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init DecryptData failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the decrypted data.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: decrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
}).catch((error: BusinessError) => {
console.error(`promise: decrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function deleteKey() {
/*
* Simulate the key deletion scenario.
*/
let emptyOptions: huks.HuksOptions = {
properties: []
}
/*
* 1. Call deleteKeyItem to delete the key.
*/
await huks.deleteKeyItem(aesKeyAlias, emptyOptions)
.then(() => {
console.info(`promise: delete data success`);
}).catch((error: BusinessError) => {
console.error(`promise: delete data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
} /*
* The following uses AES/GCM/NoPadding with promise-based APIs.
*/
import { huks } from '@kit.UniversalKeystoreKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { BusinessError } from '@kit.BasicServicesKit';
let aesKeyAlias = 'test_aesKeyAlias';
let handle: number;
let plainText = '123456';
let cipherData: Uint8Array;
let AAD = '1234567890123456';
let NONCE = cryptoFramework.createRandom().generateRandomSync(12).data;
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 uint8ArrayToString(fileData: Uint8Array) {
return Array.from(fileData, byte => String.fromCharCode(byte)).join('');
}
function getAesGenerateProperties() {
let properties: huks.HuksParam[] = [{
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_128
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}];
return properties;
}
function getAesGcmEncryptProperties() {
let properties: huks.HuksParam[] = [{
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_128
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
}, {
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: NONCE
}, {
tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
value: stringToUint8Array(AAD)
}];
return properties;
}
function getAesGcmDecryptProperties(cipherData: Uint8Array) {
let properties: huks.HuksParam[] = [{
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_128
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}, {
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: NONCE
}, {
tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
value: stringToUint8Array(AAD)
}, {
tag: huks.HuksTag.HUKS_TAG_AE_TAG,
value: cipherData.slice(cipherData.length - 16)
}];
return properties;
}
async function generateAesKey() {
/*
* Simulate the key generation scenario.
*/
/*
* 1. Obtain the parameters for key generation.
*/
let genProperties = getAesGenerateProperties();
let options: huks.HuksOptions = {
properties: genProperties
}
/*
* 2. Call generateKeyItem.
*/
await huks.generateKeyItem(aesKeyAlias, options)
.then(() => {
console.info(`promise: generate AES Key success`);
}).catch((error: BusinessError) => {
console.error(`promise: generate AES Key failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function encryptData() {
/*
* Simulate the encryption scenario.
*/
/*
* 1. Obtain the algorithm parameters for encryption.
*/
let encryptProperties = getAesGcmEncryptProperties();
let options: huks.HuksOptions = {
properties: encryptProperties,
inData: stringToUint8Array(plainText)
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(aesKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init EncryptDataGcm failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the ciphertext.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: encrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
cipherData = data.outData as Uint8Array;
}).catch((error: BusinessError) => {
console.error(`promise: encrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function decryptData() {
/*
* Simulate the decryption scenario.
*/
/*
* 1. Obtain the algorithm parameters for decryption.
*/
let decryptOptions = getAesGcmDecryptProperties(cipherData)
let options: huks.HuksOptions = {
properties: decryptOptions,
inData: cipherData.slice(0, cipherData.length - 16)
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(aesKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init DecryptDataGcm failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the decrypted data.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: decrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
}).catch((error: BusinessError) => {
console.error(`promise: decrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function deleteKey() {
/*
* Simulate the key deletion scenario.
*/
let emptyOptions: huks.HuksOptions = {
properties: []
}
/*
* 1. Call deleteKeyItem to delete the key.
*/
await huks.deleteKeyItem(aesKeyAlias, emptyOptions)
.then(() => {
console.info(`promise: delete data success`);
}).catch((error: BusinessError) => {
console.error(`promise: delete data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
} /*
* The following uses AES/CCM/NoPadding with promise-based APIs as an example.
*/
import { huks } from '@kit.UniversalKeystoreKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { BusinessError } from "@kit.BasicServicesKit";
let aesKeyAlias = 'test_aesCcmKeyAlias';
let handle: number;
let plainText = '123456';
let cipherData: Uint8Array;
let AAD = '1234567890123456';
let NONCE = cryptoFramework.createRandom().generateRandomSync(12).data;
let aeadTagLen = 14;
function StringToUint8Array(str: string) {
let arr: number[] = new Array();
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
function Uint8ArrayToString(fileData: Uint8Array) {
let dataString = '';
for (let i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]);
}
return dataString;
}
function GetAesGenerateProperties() {
let properties: Array<huks.HuksParam> = [{
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_128
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}];
return properties;
}
function GetAesCcmEncryptProperties() {
let properties: Array<huks.HuksParam> = [{
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_128
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE
}, {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_CCM
}, {
tag: huks.HuksTag.HUKS_TAG_NONCE,
value: NONCE
}, {
tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
value: StringToUint8Array(AAD)
}, {
tag: huks.HuksTag.HUKS_TAG_AE_TAG_LEN,
value: aeadTagLen
}];
return properties;
}
function GetAesCcmDecryptProperties(cipherData: Uint8Array) {
let properties: Array<huks.HuksParam> = [{
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_128
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE
}, {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_CCM
}, {
tag: huks.HuksTag.HUKS_TAG_NONCE,
value: NONCE
}, {
tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
value: StringToUint8Array(AAD)
}, {
tag: huks.HuksTag.HUKS_TAG_AE_TAG,
value: cipherData.slice(cipherData.length - aeadTagLen)
}, {
tag: huks.HuksTag.HUKS_TAG_AE_TAG_LEN,
value: aeadTagLen
}];
return properties;
}
async function GenerateAesKey() {
/*
* Simulate the key generation scenario.
* 1. Set the key alias.
*/
/*
* 2. Obtain the parameters for key generation.
*/
let genProperties = GetAesGenerateProperties();
let options: huks.HuksOptions = {
properties: genProperties
}
/*
* 3. Call generateKeyItem.
*/
await huks.generateKeyItem(aesKeyAlias, options)
.then(() => {
console.info(`promise: generate AES Key success`);
}).catch((error: BusinessError) => {
console.error(`promise: generate AES Key failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function EncryptData() {
/*
* Simulate the encryption scenario.
* 1. Obtain the key alias.
*/
/*
* 2. Obtain the data to be encrypted.
*/
/*
* 3. Obtain the algorithm parameters for encryption.
*/
let encryptProperties = GetAesCcmEncryptProperties();
let options: huks.HuksOptions = {
properties: encryptProperties,
inData: StringToUint8Array(plainText)
}
/*
* 4. Call initSession to obtain a session handle.
*/
await huks.initSession(aesKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init EncryptDataCcm failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 5. Call finishSession to obtain the ciphertext.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: encrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
cipherData = data.outData as Uint8Array;
}).catch((error: BusinessError) => {
console.error(`promise: encrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function DecryptData() {
/*
* Simulate the decryption scenario.
* 1. Obtain the key alias.
*/
/*
* 2. Obtain the ciphertext to be decrypted.
*/
/*
* 3. Obtain the algorithm parameters for decryption.
*/
let decryptOptions = GetAesCcmDecryptProperties(cipherData)
let options: huks.HuksOptions = {
properties: decryptOptions,
inData: cipherData.slice(0, cipherData.length - aeadTagLen)
}
/*
* 4. Call initSession to obtain a session handle.
*/
await huks.initSession(aesKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init DecryptDataCcm failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 5. Call finishSession to obtain the decrypted data.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: decrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
}).catch((error: BusinessError) => {
console.error(`promise: decrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function DeleteKey() {
/*
* Simulate the key deletion scenario.
* 1. Obtain the key alias.
*/
let emptyOptions: huks.HuksOptions = {
properties: []
}
/*
* 2. Call deleteKeyItem to delete the key.
*/
await huks.deleteKeyItem(aesKeyAlias, emptyOptions)
.then(() => {
console.info(`promise: delete data success`);
}).catch((error: BusinessError) => {
console.error(`promise: delete data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function TestEncryptDecrypt() {
await GenerateAesKey();
await EncryptData();
await DecryptData();
await DeleteKey();
} /*
* The following uses RSA/ECB/PKCS1_V1_5 with promise-based APIs.
*/
import { huks } from '@kit.UniversalKeystoreKit';
import { BusinessError } from '@kit.BasicServicesKit';
let rsaKeyAlias = 'test_rsaKeyAlias';
let handle: number;
let plainText = '123456';
let cipherData: Uint8Array;
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 uint8ArrayToString(fileData: Uint8Array) {
return Array.from(fileData, byte => String.fromCharCode(byte)).join('');
}
function getRsaGenerateProperties() {
let properties: huks.HuksParam[] = [{
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_2048
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}];
return properties;
}
function getRsaEncryptProperties() {
let properties: huks.HuksParam[] = [{
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_2048
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
}, {
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
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
}];
return properties;
}
function getRsaDecryptProperties() {
let properties: huks.HuksParam[] = [{
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_2048
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}, {
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
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
}];
return properties;
}
async function generateRsaKey() {
/*
* Simulate the key generation scenario.
*/
/*
* 1. Obtain the parameters for key generation.
*/
let genProperties = getRsaGenerateProperties();
let options: huks.HuksOptions = {
properties: genProperties
}
/*
* 2. Call generateKeyItem.
*/
await huks.generateKeyItem(rsaKeyAlias, options)
.then(() => {
console.info(`promise: generate RSA Key success`);
}).catch((error: BusinessError) => {
console.error(`promise: generate RSA Key failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function encryptData() {
/*
* Simulate the encryption scenario.
*/
/*
* 1. Obtain the algorithm parameters for encryption.
*/
let encryptProperties = getRsaEncryptProperties();
let options: huks.HuksOptions = {
properties: encryptProperties,
inData: stringToUint8Array(plainText)
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(rsaKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init EncryptDataRsa failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the ciphertext.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: encrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
cipherData = data.outData as Uint8Array;
}).catch((error: BusinessError) => {
console.error(`promise: encrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function decryptData() {
/*
* Simulate the decryption scenario.
*/
/*
* 1. Obtain the algorithm parameters for decryption.
*/
let decryptOptions = getRsaDecryptProperties()
let options: huks.HuksOptions = {
properties: decryptOptions,
inData: cipherData
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(rsaKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init DecryptDataRsa failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the decrypted data.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: decrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
}).catch((error: BusinessError) => {
console.error(`promise: decrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function deleteKey() {
/*
* Simulate the key deletion scenario.
*/
let emptyOptions: huks.HuksOptions = {
properties: []
}
/*
* 1. Call deleteKeyItem to delete the key.
*/
await huks.deleteKeyItem(rsaKeyAlias, emptyOptions)
.then(() => {
console.info(`promise: delete data success`);
}).catch((error: BusinessError) => {
console.error(`promise: delete data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
} /*
* The following uses RSA/ECB/OAEP/SHA-256 with promise-based APIs.
*/
import { huks } from '@kit.UniversalKeystoreKit';
import { BusinessError } from '@kit.BasicServicesKit';
let rsaKeyAlias = 'test_rsaKeyAlias';
let handle: number;
let plainText = '123456';
let cipherData: Uint8Array;
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 uint8ArrayToString(fileData: Uint8Array) {
return Array.from(fileData, byte => String.fromCharCode(byte)).join('');
}
function getRsaGenerateProperties() {
let properties: huks.HuksParam[] = [{
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_2048
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}];
return properties;
}
function getRsaEncryptProperties() {
let properties: huks.HuksParam[] = [{
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_2048
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
}, {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}];
return properties;
}
function getRsaDecryptProperties() {
let properties: huks.HuksParam[] = [{
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_2048
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
}, {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}];
return properties;
}
async function generateRsaKey() {
/*
* Simulate the key generation scenario.
*/
/*
* 1. Obtain the parameters for key generation.
*/
let genProperties = getRsaGenerateProperties();
let options: huks.HuksOptions = {
properties: genProperties
}
/*
* 2. Call generateKeyItem.
*/
await huks.generateKeyItem(rsaKeyAlias, options)
.then(() => {
console.info(`promise: generate RSA Key success`);
}).catch((error: BusinessError) => {
console.error(`promise: generate RSA Key failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function encryptData() {
/*
* Simulate the encryption scenario.
*/
/*
* 1. Obtain the algorithm parameters for encryption.
*/
let encryptProperties = getRsaEncryptProperties();
let options: huks.HuksOptions = {
properties: encryptProperties,
inData: stringToUint8Array(plainText)
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(rsaKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init EncryptDataRsa failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the ciphertext.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: encrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
cipherData = data.outData as Uint8Array;
}).catch((error: BusinessError) => {
console.error(`promise: encrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function decryptData() {
/*
* Simulate the decryption scenario.
*/
/*
* 1. Obtain the algorithm parameters for decryption.
*/
let decryptOptions = getRsaDecryptProperties()
let options: huks.HuksOptions = {
properties: decryptOptions,
inData: cipherData
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(rsaKeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init DecryptDataRsa failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the decrypted data.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: decrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
}).catch((error: BusinessError) => {
console.error(`promise: decrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function deleteKey() {
/*
* Simulate the key deletion scenario.
*/
let emptyOptions: huks.HuksOptions = {
properties: []
}
/*
* 1. Call deleteKeyItem to delete the key.
*/
await huks.deleteKeyItem(rsaKeyAlias, emptyOptions)
.then(() => {
console.info(`promise: delete data success`);
}).catch((error: BusinessError) => {
console.error(`promise: delete data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
} /*
* The following uses SM2 with promise-based APIs.
*/
import { huks } from '@kit.UniversalKeystoreKit';
import { BusinessError } from '@kit.BasicServicesKit';
let sm2KeyAlias = 'test_sm2KeyAlias';
let handle: number;
let plainText = '123456';
let cipherData: Uint8Array;
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 uint8ArrayToString(fileData: Uint8Array) {
return Array.from(fileData, byte => String.fromCharCode(byte)).join('');
}
function getSm2GenerateProperties() {
let properties: huks.HuksParam[] = [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_SM2
}, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}];
return properties;
}
function getSm2EncryptProperties() {
let properties: huks.HuksParam[] = [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_SM2
}, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SM3
}];
return properties;
}
function getSm2DecryptProperties() {
let properties: huks.HuksParam[] = [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_SM2
}, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256
}, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}, {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SM3
}];
return properties;
}
async function generateSm2Key() {
/*
* Simulate the key generation scenario.
*/
/*
* 1. Obtain the parameters for key generation.
*/
let genProperties = getSm2GenerateProperties();
let options: huks.HuksOptions = {
properties: genProperties
}
/*
* 2. Call generateKeyItem.
*/
await huks.generateKeyItem(sm2KeyAlias, options)
.then(() => {
console.info(`promise: generate SM2 Key success`);
}).catch((error: BusinessError) => {
console.error(`promise: generate SM2 Key failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function encryptDataSm2() {
/*
* Simulate the encryption scenario.
*/
/*
* 1. Obtain the algorithm parameters for encryption.
*/
let encryptProperties = getSm2EncryptProperties();
let options: huks.HuksOptions = {
properties: encryptProperties,
inData: stringToUint8Array(plainText)
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(sm2KeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init EncryptDataSm2 failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the ciphertext.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: encrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
cipherData = data.outData as Uint8Array;
}).catch((error: BusinessError) => {
console.error(`promise: encrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function decryptDataSm2() {
/*
* Simulate the decryption scenario.
*/
/*
* 1. Obtain the algorithm parameters for decryption.
*/
let decryptOptions = getSm2DecryptProperties()
let options: huks.HuksOptions = {
properties: decryptOptions,
inData: cipherData
}
/*
* 2. Call initSession to obtain a session handle.
*/
await huks.initSession(sm2KeyAlias, options)
.then((data) => {
handle = data.handle;
}).catch((error: BusinessError) => {
console.error(`promise: init DecryptDataSm2 failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
/*
* 3. Call finishSession to obtain the decrypted data.
*/
await huks.finishSession(handle, options)
.then((data) => {
console.info(`promise: decrypt data success, data is ` + uint8ArrayToString(data.outData as Uint8Array));
}).catch((error: BusinessError) => {
console.error(`promise: decrypt data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}
async function deleteKey() {
/*
* Simulate the key deletion scenario.
*/
let emptyOptions: huks.HuksOptions = {
properties: []
}
/*
* 1. Call deleteKeyItem to delete the key.
*/
await huks.deleteKeyItem(sm2KeyAlias, emptyOptions)
.then(() => {
console.info(`promise: delete data success`);
}).catch((error: BusinessError) => {
console.error(`promise: delete data failed, errCode : ${error.code}, errMsg : ${error.message}`);
})
}