DEV Community

SameX
SameX

Posted on

HarmonyOS Next: The Integration of Device Certificate Kit and Crypto Architecture Kit

This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now), and is summarized based on actual development practices. It mainly serves as a vehicle for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.
In the security world of Huawei HarmonyOS, the Device Certificate Kit and the Crypto Architecture Kit are like a pair of partners with perfect teamwork, working together to ensure encryption security. Today, let's take an in-depth look at how they collaborate to safeguard our devices and applications.
Firstly, let's understand the collaborative working mechanism of these two kits. The Device Certificate Kit is mainly responsible for the management and verification of certificates, while the Crypto Architecture Kit focuses on the implementation of encryption and decryption algorithms. When we need to verify the authenticity of a device, the Device Certificate Kit can utilize its certificate management functions to obtain the certificate information of the device, which includes the public key. Then, this public key is passed to the Crypto Architecture Kit, and it will carry out the subsequent encryption operations. It's just like one is responsible for providing the key (the public key), and the other uses this key to lock the door (encrypt) or open the door (decrypt). They complement each other and are indispensable.
Next, let's see how to generate and obtain the public key and use it for device authenticity verification. Suppose we are in an application scenario that requires device authentication. First, we need to use the Device Certificate Kit to create an application public-private key pair (including the application public key and the application private key). Here, we take the RSA or EC algorithm as an example. The sample code is as follows:

import { huks } from '@kit.UniversalKeystoreKit';
import { BusinessError } from '@kit.BasicServicesKit';
let keyAlias ='serviceKey';
function GetGenerateProperties() {
    let properties: Array<huks.HuksParam> = new Array();
    let index = 0;
    properties[index++] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_ECC
    };
    properties[index++] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
    };
    properties[index++] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
            huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
    };
    properties[index++] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    }
    return properties;
}
async function GenerateKey(keyAlias: string) {
    let genProperties = GetGenerateProperties();
    let options: huks.HuksOptions = {
        properties: genProperties
    }
    await huks.generateKeyItem(keyAlias, options)
     .then(() => {
            console.info(`promise: generate Key success.`);
        }).catch((err: BusinessError) => {
            console.error(`promise: generate Key failed, error: ` + err.message);
        })
}
Enter fullscreen mode Exit fullscreen mode

After generating the public-private key pair, we can obtain the application public key through the Device Certificate Kit and use it for device authenticity verification. For example, when communicating with a server, the public key is sent to the server, and the server can use the public key to verify the data sent by the device to ensure that the data comes from a genuine device.
Then, let's understand the process of secure encryption using the Crypto Architecture Kit. Suppose we want to encrypt a piece of data. First, we need to initialize the encryption algorithm, then pass in the data for the encryption operation, and finally obtain the encryption result. Here is a simple example of using the HMAC algorithm to calculate the message authentication code (this is just an example, and in actual applications, an appropriate encryption algorithm can be selected according to requirements):

import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer } from '@kit.ArkTS';
async function doHmac() {
    // Decode the string to Uint8Array according to utf-8, using a fixed 128-bit key, that is, 16 bytes
    let keyData = new Uint8Array(buffer.from("12345678abcdefgh", 'utf - 8').buffer);
    let key = await genSymKeyByData(keyData);
    let macAlgName = 'SHA256';
    let message = 'hmacTestMessgae';
    let mac = cryptoFramework.createMac(macAlgName);
    await mac.init(key);
    // When the amount of data is small, you can do only one update and pass in all the data. The interface does not limit the length of the input parameter.
    await mac.update({ data: new Uint8Array(buffer.from(message, 'utf - 8').buffer) });
    let macResult = await mac.doFinal();
    console.info('HMAC result:' + macResult.data);
    let macLen = mac.getMacLength();
    console.info('HMAC len:' + macLen);
}
Enter fullscreen mode Exit fullscreen mode

To show the functional differences and connections between the Device Certificate Kit and the Crypto Architecture Kit more clearly, let's look at a module function comparison table:
| Functional Module | Device Certificate Kit | Crypto Architecture Kit |
| ---- | ---- | ---- |
| Main Functions | Certificate management (installation, storage, use, destruction), certificate verification, certificate chain validation, etc. | Implementation of encryption and decryption algorithms (such as message authentication code calculation, message digest calculation, symmetric and asymmetric encryption, etc.). |
| Data Processing Objects | Certificates and related information (such as certificate chains, certificate extension fields, certificate revocation lists, etc.). | Raw data (such as the message to be encrypted, the data for which the digest is to be calculated, etc.). |
| Security Goal Emphasis | Ensure the authenticity of device identity, the legality of certificates, and the integrity of the trust chain. | Ensure the confidentiality, integrity, and authenticity of data during transmission and storage. |
Through this table, we can clearly see the differences and complementary aspects of the two kits in terms of functions.
In conclusion, the linkage between the Device Certificate Kit and the Crypto Architecture Kit provides a powerful encryption security guarantee for the HarmonyOS system. They are like two guardian angels, with one safeguarding the device's identity authentication and the other safeguarding the encryption security of data. In practical applications, developers should fully understand and utilize their collaborative working mechanism, reasonably call relevant functions according to specific requirements, and ensure the security of applications. It's like forming a basketball team, where each player has their own position and responsibilities, and only by cooperating with each other can they win the game. I hope that on the road of HarmonyOS development, everyone can skillfully use these two tools to create impregnable secure applications. If you encounter problems during the use process, don't be discouraged. Think more and try more, and I believe you will surely be able to overcome the difficulties. Come on, fellow developer friends!

Top comments (0)