diff --git a/zh-cn/application-dev/security/Readme-CN.md b/zh-cn/application-dev/security/Readme-CN.md index af608f4bf4e0ca46bad71e67b842062b5027842b..27f4f72cc3a8ce6e4c432f3e92604b4c2f8231cd 100644 --- a/zh-cn/application-dev/security/Readme-CN.md +++ b/zh-cn/application-dev/security/Readme-CN.md @@ -9,8 +9,9 @@ - [用户认证开发概述](userauth-overview.md) - [用户认证开发指导](userauth-guidelines.md) - 密钥管理 - - [HUKS开发概述](huks-overview.md) - - [HUKS开发指导](huks-guidelines.md) + - [通用密钥库开发概述](huks-overview.md) + - [通用密钥库开发指导](huks-guidelines.md) + - [通用密钥库密码算法规格](huks-appendix.md) - 加密算法库框架 - [加密算法库框架概述](cryptoFramework-overview.md) - [加密算法框架开发指导](cryptoFramework-guidelines.md) diff --git a/zh-cn/application-dev/security/figures/huks_architect.png b/zh-cn/application-dev/security/figures/huks_architect.png new file mode 100644 index 0000000000000000000000000000000000000000..25d98954291e237644b5937308545804499c90f4 Binary files /dev/null and b/zh-cn/application-dev/security/figures/huks_architect.png differ diff --git a/zh-cn/application-dev/security/figures/huks_import_wrapped_key.png b/zh-cn/application-dev/security/figures/huks_import_wrapped_key.png new file mode 100644 index 0000000000000000000000000000000000000000..61d08ee1414ac2da6d3acf7310061a35177ce238 Binary files /dev/null and b/zh-cn/application-dev/security/figures/huks_import_wrapped_key.png differ diff --git a/zh-cn/application-dev/security/figures/huks_key_user_auth_work_flow.png b/zh-cn/application-dev/security/figures/huks_key_user_auth_work_flow.png new file mode 100644 index 0000000000000000000000000000000000000000..9bec19fe3886a5c8f13d261fa6473314d7388f1e Binary files /dev/null and b/zh-cn/application-dev/security/figures/huks_key_user_auth_work_flow.png differ diff --git a/zh-cn/application-dev/security/figures/huks_keymaterial_rsa_priv_struct.png b/zh-cn/application-dev/security/figures/huks_keymaterial_rsa_priv_struct.png new file mode 100644 index 0000000000000000000000000000000000000000..f22b578929b98877b1b8adbcb5623dba004269ed Binary files /dev/null and b/zh-cn/application-dev/security/figures/huks_keymaterial_rsa_priv_struct.png differ diff --git a/zh-cn/application-dev/security/figures/huks_keymaterial_struct.png b/zh-cn/application-dev/security/figures/huks_keymaterial_struct.png new file mode 100644 index 0000000000000000000000000000000000000000..4aa3e3c4e7df818c757cf0f66b224560bc6d9110 Binary files /dev/null and b/zh-cn/application-dev/security/figures/huks_keymaterial_struct.png differ diff --git a/zh-cn/application-dev/security/huks-appendix.md b/zh-cn/application-dev/security/huks-appendix.md new file mode 100644 index 0000000000000000000000000000000000000000..317d78b22dd3088f4179a83d62238bdb97048526 --- /dev/null +++ b/zh-cn/application-dev/security/huks-appendix.md @@ -0,0 +1,227 @@ +# 通用密钥库密码算法规格 + +## 支持的算法类型及参数组合 + +### 导入\生成密钥规格 + +| 算法                    | API级别 | 支持的密钥长度 | +| -------------- | :---------------: | ------------------ | +| AES | 8+ | 128、192、256 | +| RSA | 8+ | 512、768、1024、2048、3072、4096 | +| HMAC | 8+ | 8-1024(含),必须是8的倍数 | +| ECC | 8+ | 224、256、384、521 | +| ED25519 | 8+ | 256 | +| X25519 | 8+ | 256 | +| DSA | 8+ | 8-1024(含),8的倍数 | +| DH | 8+ | 2048、3072、4096 | +| SM2 | 9+ | 256 | +| SM3 | 9+ | 256 | +| SM4 | 9+ | 128 | + +### 加密解密 + +| 算法                    | API级别 | 备注 | +| ----------------------- | :----: | ---------------- | +| AES/CBC/NoPadding
AES/ECB/NoPadding
AES/CTR/NoPadding
AES/GCM/NoPadding
AES/CBC/PKCS7
AES/ECB/PKCS7 | 8+ | 1. CBC\ECB\CTR模式IV参数必选
2. GCM模式下Nonce、AAD、AEAD参数必选 | +| RSA/ECB/NoPadding
RSA/ECB/PKCS1_V1_5
RSA/ECB/OAEP | 8+ | | +| SM4/CTR/NoPadding
SM4/ECB/NoPadding
SM4/CBC/NoPadding
SM4/ECB/PKCS7
SM4/CBC/PKCS7 | 9+ | | + + + +### 签名验签 + + +| 算法 | API级别 | 备注 | +| --------- | :----------: | ----------------- | +| RSA/MD5/PKCS1_V1_5
RSA/SHA1/PKCS1_V1_5
RSA/SHA224/PKCS1_V1_5
RSA/SHA256/PKCS1_V1_5
RSA/SHA384/PKCS1_V1_5
RSA/SHA512/PKCS1_V1_5
RSA/SHA1/PSS
RSA/SHA224/PSS
RSA/SHA256/PSS
RSA/SHA384/PSS | 8+ | | +| RSA/NoDigest/PKCS1_V1_5 | 9+ | | +| DSA/SHA1
DSA/SHA224
DSA/SHA256
DSA/SHA384
DSA/SHA512 | 8+ | | +| DSA/NoDigest | 9+ | | +| ECC/SHA1
ECC/SHA224
ECC/SHA256
ECC/SHA384
ECC/SHA512 | 8+ | | +| ECC/NoDigest | 9+ | | +| ED25519/SHA1
ED25519/SHA224
ED25519/SHA256
ED25519/SHA384
ED25519/SHA512 |8+ | | +| ED25519/NoDigest | 9+ | | +| SM2/SM3
SM2/NoDigest |9+ | | + +### 密钥协商 + +| 算法                    | API级别 | 备注 | +| ------ | :-----------: | ------------------------------ | +| ECDH | 8+ | 协商密钥类型为ECC类型密钥 | +| DH | 8+ | | +| X25519 | 8+ | | + +### 密钥派生 + +| 算法                    |API级别 | 派生密钥及长度 | 备注 | +| ------------------------- | :-----------: | ------------ | ----------------- | +| HKDF/SHA256
HKDF/SHA384
HKDF/SHA512 | 8+ | 算法:AES、HMAC、SM4 长度:256、384、512 | 派生出的密钥可以存储到HUKS或者直接返回明文 | +| PBKDF2/SHA256
PBKDF2/SHA384
PBKDF2/SHA512 | 8+ | 算法:AES、HMAC、SM4 长度:256、384、512 | 派生出的密钥可以存储到HUKS或者直接返回明文 | + +### 密钥证明 + +| 算法                    |API级别 | 备注 | +| ------------------ | :-----: | ------------------------------------------------------------ | +| RSA | 9+ | 仅支持Padding为PSS的密钥 | +| ECC | 9+ | | +| X25519 | 9+ | | + +## 密钥材料格式 +针对不同密码算法的密钥对、公钥、私钥,HUKS定义了一套密钥材料格式。 + +### 密钥对材料 +**密钥对材料 = 密钥对材料Header + 密钥对材料原文** + +以RSA密钥为例,应用需要申请一个Uint8Array,按照RSA密钥对材料内存格式,将各个变量赋值到对应的位置: + +**图4** RSA密钥材料内存结构 + +![huks_keymaterial_struct](figures/huks_keymaterial_struct.png) + +```ts +let rsa2048KeyPairMaterial = new Uint8Array([ + 0x01, 0x00, 0x00, 0x00, // 密钥算法:huks.HuksKeyAlg.HUKS_ALG_RSA = 1 + 0x00, 0x08, 0x00, 0x00, // 密钥大小(比特):2048 + 0x00, 0x01, 0x00, 0x00, // 模数n长度(字节):256 + 0x03, 0x00, 0x00, 0x00, // 公钥指数e长度(字节):3 + 0x00, 0x01, 0x00, 0x00, // 私钥指数d长度(字节):256 + // 模数n + 0xc5, 0x35, 0x62, 0x48, 0xc4, 0x92, 0x87, 0x73, 0x0d, 0x42, 0x96, 0xfc, 0x7b, 0x11, 0x05, 0x06, + 0x0f, 0x8d, 0x66, 0xc1, 0x0e, 0xad, 0x37, 0x44, 0x92, 0x95, 0x2f, 0x6a, 0x55, 0xba, 0xec, 0x1d, + 0x54, 0x62, 0x0a, 0x4b, 0xd3, 0xc7, 0x05, 0xe4, 0x07, 0x40, 0xd9, 0xb7, 0xc2, 0x12, 0xcb, 0x9a, + 0x90, 0xad, 0xe3, 0x24, 0xe8, 0x5e, 0xa6, 0xf8, 0xd0, 0x6e, 0xbc, 0xd1, 0x69, 0x7f, 0x6b, 0xe4, + 0x2b, 0x4e, 0x1a, 0x65, 0xbb, 0x73, 0x88, 0x6b, 0x7c, 0xaf, 0x7e, 0xd0, 0x47, 0x26, 0xeb, 0xa5, + 0xbe, 0xd6, 0xe8, 0xee, 0x9c, 0xa5, 0x66, 0xa5, 0xc9, 0xd3, 0x25, 0x13, 0xc4, 0x0e, 0x6c, 0xab, + 0x50, 0xb6, 0x50, 0xc9, 0xce, 0x8f, 0x0a, 0x0b, 0xc6, 0x28, 0x69, 0xe9, 0x83, 0x69, 0xde, 0x42, + 0x56, 0x79, 0x7f, 0xde, 0x86, 0x24, 0xca, 0xfc, 0xaa, 0xc0, 0xf3, 0xf3, 0x7f, 0x92, 0x8e, 0x8a, + 0x12, 0x52, 0xfe, 0x50, 0xb1, 0x5e, 0x8c, 0x01, 0xce, 0xfc, 0x7e, 0xf2, 0x4f, 0x5f, 0x03, 0xfe, + 0xa7, 0xcd, 0xa1, 0xfc, 0x94, 0x52, 0x00, 0x8b, 0x9b, 0x7f, 0x09, 0xab, 0xa8, 0xa4, 0xf5, 0xb4, + 0xa5, 0xaa, 0xfc, 0x72, 0xeb, 0x17, 0x40, 0xa9, 0xee, 0xbe, 0x8f, 0xc2, 0xd1, 0x80, 0xc2, 0x0d, + 0x44, 0xa9, 0x59, 0x44, 0x59, 0x81, 0x3b, 0x5d, 0x4a, 0xde, 0xfb, 0xae, 0x24, 0xfc, 0xa3, 0xd9, + 0xbc, 0x57, 0x55, 0xc2, 0x26, 0xbc, 0x19, 0xa7, 0x9a, 0xc5, 0x59, 0xa3, 0xee, 0x5a, 0xef, 0x41, + 0x80, 0x7d, 0xf8, 0x5e, 0xc1, 0x1d, 0x32, 0x38, 0x41, 0x5b, 0xb6, 0x92, 0xb8, 0xb7, 0x03, 0x0d, + 0x3e, 0x59, 0x0f, 0x1c, 0xb3, 0xe1, 0x2a, 0x95, 0x1a, 0x3b, 0x50, 0x4f, 0xc4, 0x1d, 0xcf, 0x73, + 0x7c, 0x14, 0xca, 0xe3, 0x0b, 0xa7, 0xc7, 0x1a, 0x41, 0x4a, 0xee, 0xbe, 0x1f, 0x43, 0xdd, 0xf9, + // 公钥指数e + 0x01, 0x00, 0x01, + // 私钥指数d + 0x88, 0x4b, 0x82, 0xe7, 0xe3, 0xe3, 0x99, 0x75, 0x6c, 0x9e, 0xaf, 0x17, 0x44, 0x3e, 0xd9, 0x07, + 0xfd, 0x4b, 0xae, 0xce, 0x92, 0xc4, 0x28, 0x44, 0x5e, 0x42, 0x79, 0x08, 0xb6, 0xc3, 0x7f, 0x58, + 0x2d, 0xef, 0xac, 0x4a, 0x07, 0xcd, 0xaf, 0x46, 0x8f, 0xb4, 0xc4, 0x43, 0xf9, 0xff, 0x5f, 0x74, + 0x2d, 0xb5, 0xe0, 0x1c, 0xab, 0xf4, 0x6e, 0xd5, 0xdb, 0xc8, 0x0c, 0xfb, 0x76, 0x3c, 0x38, 0x66, + 0xf3, 0x7f, 0x01, 0x43, 0x7a, 0x30, 0x39, 0x02, 0x80, 0xa4, 0x11, 0xb3, 0x04, 0xd9, 0xe3, 0x57, + 0x23, 0xf4, 0x07, 0xfc, 0x91, 0x8a, 0xc6, 0xcc, 0xa2, 0x16, 0x29, 0xb3, 0xe5, 0x76, 0x4a, 0xa8, + 0x84, 0x19, 0xdc, 0xef, 0xfc, 0xb0, 0x63, 0x33, 0x0b, 0xfa, 0xf6, 0x68, 0x0b, 0x08, 0xea, 0x31, + 0x52, 0xee, 0x99, 0xef, 0x43, 0x2a, 0xbe, 0x97, 0xad, 0xb3, 0xb9, 0x66, 0x7a, 0xae, 0xe1, 0x8f, + 0x57, 0x86, 0xe5, 0xfe, 0x14, 0x3c, 0x81, 0xd0, 0x64, 0xf8, 0x86, 0x1a, 0x0b, 0x40, 0x58, 0xc9, + 0x33, 0x49, 0xb8, 0x99, 0xc6, 0x2e, 0x94, 0x70, 0xee, 0x09, 0x88, 0xe1, 0x5c, 0x4e, 0x6c, 0x22, + 0x72, 0xa7, 0x2a, 0x21, 0xdd, 0xd7, 0x1d, 0xfc, 0x63, 0x15, 0x0b, 0xde, 0x06, 0x9c, 0xf3, 0x28, + 0xf3, 0xac, 0x4a, 0xa8, 0xb5, 0x50, 0xca, 0x9b, 0xcc, 0x0a, 0x04, 0xfe, 0x3f, 0x98, 0x68, 0x81, + 0xac, 0x24, 0x53, 0xea, 0x1f, 0x1c, 0x6e, 0x5e, 0xca, 0xe8, 0x31, 0x0d, 0x08, 0x12, 0xf3, 0x26, + 0xf8, 0x5e, 0xeb, 0x10, 0x27, 0xae, 0xaa, 0xc3, 0xad, 0x6c, 0xc1, 0x89, 0xdb, 0x7d, 0x5a, 0x12, + 0x55, 0xad, 0x11, 0x19, 0xa1, 0xa9, 0x8f, 0x0b, 0x6d, 0x78, 0x8d, 0x1c, 0xdf, 0xe5, 0x63, 0x82, + 0x0b, 0x7d, 0x23, 0x04, 0xb4, 0x75, 0x8c, 0xed, 0x77, 0xfc, 0x1a, 0x85, 0x29, 0x11, 0xe0, 0x61, + ]); +``` + +其中,密钥算法的值取自枚举类[HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg)。 + +- **RSA密钥对材料格式:** + | 密钥算法 | 密钥大小 | 模数n长度Ln | 公钥指数e长度Le | 私钥指数d长度Ld | n | e | d | + | :----: |:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4字节|4字节|4字节|4字节|4字节|Ln字节 |Le字节 |Ld字节 | + + +- **ECC密钥对材料格式:** + | 密钥算法 | 密钥大小 | 坐标x长度Lx | 坐标y长度Ly | 坐标z长度Lz | x | y | z | + | :----: |:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4字节|4字节|4字节|4字节|4字节|Lx字节 |Ly字节 |Lz字节 | + + +- **DSA密钥对材料格式:** + | 密钥算法 | 密钥大小 | 私钥x长度Lx | 公钥y长度Ly | 素数p长度Lp | 素因子q长度Lq | g长度Lg | x | y | p | q | g | + | :----: |:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4字节|4字节|4字节|4字节|4字节|4字节|4字节|Lx字节 |Ly字节 |Lp字节 |Lq字节 |Lg字节 | + + +- **DH密钥对材料格式:** + | 密钥算法 | 密钥大小 | 公钥pk长度Lpk | 私钥sk长度Lsk | 保留字段 | pk | sk | + |:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4字节|4字节|4字节|4字节|4字节|Lpk字节 |Lsk字节 | + + +- **Curve25519密钥对材料格式:** + | 密钥算法 | 密钥大小 | 公钥pk长度Lpk | 私钥sk长度Lsk | 保留字段 | pk | sk | + |:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4字节|4字节|4字节|4字节|4字节|Lpk字节 |Lsk字节 | + + +### 公钥材料 + +在公钥导出/导入时,密钥材料采用标准的X.509规范的DER格式封装。 + +如下是一个DER编码的ECC公钥: +```ts +let eccP256PubKey = new Uint8Array([ + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, + 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe, 0x1c, 0x67, 0xde, + 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2, + 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99, 0x3d, 0xe8, + 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44, + 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e]); +``` + +### 私钥材料 + +复用密钥对的材料格式,私钥材料的封装是把密钥对材料Header中的公钥部分的长度字段置0,同时密钥对材料原文部分拼接私钥材料即可。 + +**私钥材料 = 密钥对材料Header + 私钥材料原文** + +以RSA私钥材料为例: + +![huks_keymaterial_rsa_priv_struct](figures/huks_keymaterial_rsa_priv_struct.png) + +```ts +let rsa2048PrivateKeyMaterial = new Uint8Array([ + 0x01, 0x00, 0x00, 0x00, // 密钥算法:huks.HuksKeyAlg.HUKS_ALG_RSA = 1 + 0x00, 0x08, 0x00, 0x00, // 密钥大小(比特):2048 + 0x00, 0x01, 0x00, 0x00, // 模数n长度(字节):256 + 0x00, 0x00, 0x00, 0x00, // 公钥指数e长度(字节):0 + 0x00, 0x01, 0x00, 0x00, // 私钥指数d长度(字节):256 + // 模数n + 0xc5, 0x35, 0x62, 0x48, 0xc4, 0x92, 0x87, 0x73, 0x0d, 0x42, 0x96, 0xfc, 0x7b, 0x11, 0x05, 0x06, + 0x0f, 0x8d, 0x66, 0xc1, 0x0e, 0xad, 0x37, 0x44, 0x92, 0x95, 0x2f, 0x6a, 0x55, 0xba, 0xec, 0x1d, + 0x54, 0x62, 0x0a, 0x4b, 0xd3, 0xc7, 0x05, 0xe4, 0x07, 0x40, 0xd9, 0xb7, 0xc2, 0x12, 0xcb, 0x9a, + 0x90, 0xad, 0xe3, 0x24, 0xe8, 0x5e, 0xa6, 0xf8, 0xd0, 0x6e, 0xbc, 0xd1, 0x69, 0x7f, 0x6b, 0xe4, + 0x2b, 0x4e, 0x1a, 0x65, 0xbb, 0x73, 0x88, 0x6b, 0x7c, 0xaf, 0x7e, 0xd0, 0x47, 0x26, 0xeb, 0xa5, + 0xbe, 0xd6, 0xe8, 0xee, 0x9c, 0xa5, 0x66, 0xa5, 0xc9, 0xd3, 0x25, 0x13, 0xc4, 0x0e, 0x6c, 0xab, + 0x50, 0xb6, 0x50, 0xc9, 0xce, 0x8f, 0x0a, 0x0b, 0xc6, 0x28, 0x69, 0xe9, 0x83, 0x69, 0xde, 0x42, + 0x56, 0x79, 0x7f, 0xde, 0x86, 0x24, 0xca, 0xfc, 0xaa, 0xc0, 0xf3, 0xf3, 0x7f, 0x92, 0x8e, 0x8a, + 0x12, 0x52, 0xfe, 0x50, 0xb1, 0x5e, 0x8c, 0x01, 0xce, 0xfc, 0x7e, 0xf2, 0x4f, 0x5f, 0x03, 0xfe, + 0xa7, 0xcd, 0xa1, 0xfc, 0x94, 0x52, 0x00, 0x8b, 0x9b, 0x7f, 0x09, 0xab, 0xa8, 0xa4, 0xf5, 0xb4, + 0xa5, 0xaa, 0xfc, 0x72, 0xeb, 0x17, 0x40, 0xa9, 0xee, 0xbe, 0x8f, 0xc2, 0xd1, 0x80, 0xc2, 0x0d, + 0x44, 0xa9, 0x59, 0x44, 0x59, 0x81, 0x3b, 0x5d, 0x4a, 0xde, 0xfb, 0xae, 0x24, 0xfc, 0xa3, 0xd9, + 0xbc, 0x57, 0x55, 0xc2, 0x26, 0xbc, 0x19, 0xa7, 0x9a, 0xc5, 0x59, 0xa3, 0xee, 0x5a, 0xef, 0x41, + 0x80, 0x7d, 0xf8, 0x5e, 0xc1, 0x1d, 0x32, 0x38, 0x41, 0x5b, 0xb6, 0x92, 0xb8, 0xb7, 0x03, 0x0d, + 0x3e, 0x59, 0x0f, 0x1c, 0xb3, 0xe1, 0x2a, 0x95, 0x1a, 0x3b, 0x50, 0x4f, 0xc4, 0x1d, 0xcf, 0x73, + 0x7c, 0x14, 0xca, 0xe3, 0x0b, 0xa7, 0xc7, 0x1a, 0x41, 0x4a, 0xee, 0xbe, 0x1f, 0x43, 0xdd, 0xf9, + // 私钥指数d + 0x88, 0x4b, 0x82, 0xe7, 0xe3, 0xe3, 0x99, 0x75, 0x6c, 0x9e, 0xaf, 0x17, 0x44, 0x3e, 0xd9, 0x07, + 0xfd, 0x4b, 0xae, 0xce, 0x92, 0xc4, 0x28, 0x44, 0x5e, 0x42, 0x79, 0x08, 0xb6, 0xc3, 0x7f, 0x58, + 0x2d, 0xef, 0xac, 0x4a, 0x07, 0xcd, 0xaf, 0x46, 0x8f, 0xb4, 0xc4, 0x43, 0xf9, 0xff, 0x5f, 0x74, + 0x2d, 0xb5, 0xe0, 0x1c, 0xab, 0xf4, 0x6e, 0xd5, 0xdb, 0xc8, 0x0c, 0xfb, 0x76, 0x3c, 0x38, 0x66, + 0xf3, 0x7f, 0x01, 0x43, 0x7a, 0x30, 0x39, 0x02, 0x80, 0xa4, 0x11, 0xb3, 0x04, 0xd9, 0xe3, 0x57, + 0x23, 0xf4, 0x07, 0xfc, 0x91, 0x8a, 0xc6, 0xcc, 0xa2, 0x16, 0x29, 0xb3, 0xe5, 0x76, 0x4a, 0xa8, + 0x84, 0x19, 0xdc, 0xef, 0xfc, 0xb0, 0x63, 0x33, 0x0b, 0xfa, 0xf6, 0x68, 0x0b, 0x08, 0xea, 0x31, + 0x52, 0xee, 0x99, 0xef, 0x43, 0x2a, 0xbe, 0x97, 0xad, 0xb3, 0xb9, 0x66, 0x7a, 0xae, 0xe1, 0x8f, + 0x57, 0x86, 0xe5, 0xfe, 0x14, 0x3c, 0x81, 0xd0, 0x64, 0xf8, 0x86, 0x1a, 0x0b, 0x40, 0x58, 0xc9, + 0x33, 0x49, 0xb8, 0x99, 0xc6, 0x2e, 0x94, 0x70, 0xee, 0x09, 0x88, 0xe1, 0x5c, 0x4e, 0x6c, 0x22, + 0x72, 0xa7, 0x2a, 0x21, 0xdd, 0xd7, 0x1d, 0xfc, 0x63, 0x15, 0x0b, 0xde, 0x06, 0x9c, 0xf3, 0x28, + 0xf3, 0xac, 0x4a, 0xa8, 0xb5, 0x50, 0xca, 0x9b, 0xcc, 0x0a, 0x04, 0xfe, 0x3f, 0x98, 0x68, 0x81, + 0xac, 0x24, 0x53, 0xea, 0x1f, 0x1c, 0x6e, 0x5e, 0xca, 0xe8, 0x31, 0x0d, 0x08, 0x12, 0xf3, 0x26, + 0xf8, 0x5e, 0xeb, 0x10, 0x27, 0xae, 0xaa, 0xc3, 0xad, 0x6c, 0xc1, 0x89, 0xdb, 0x7d, 0x5a, 0x12, + 0x55, 0xad, 0x11, 0x19, 0xa1, 0xa9, 0x8f, 0x0b, 0x6d, 0x78, 0x8d, 0x1c, 0xdf, 0xe5, 0x63, 0x82, + 0x0b, 0x7d, 0x23, 0x04, 0xb4, 0x75, 0x8c, 0xed, 0x77, 0xfc, 0x1a, 0x85, 0x29, 0x11, 0xe0, 0x61, + ]); +``` + diff --git a/zh-cn/application-dev/security/huks-guidelines.md b/zh-cn/application-dev/security/huks-guidelines.md index 4e5cd92fe3290a04393f81ec3afc306d44178ad5..fb0922ed99056d703130194a0b30de0228f76be8 100644 --- a/zh-cn/application-dev/security/huks-guidelines.md +++ b/zh-cn/application-dev/security/huks-guidelines.md @@ -1,186 +1,361 @@ -# HUKS开发指导 -HUKS(OpenHarmony Universal KeyStore,OpenHarmony通用密钥库系统)向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成。 +# 通用密钥库开发指导 + +## 生成新密钥 + +HUKS提供为业务安全随机生成密钥的能力。通过HUKS生成的密钥,密钥的全生命周期明文不会出安全环境,能保证任何人都无法接触获取到密钥的明文。即使生成密钥的业务自身,后续也只能通过HUKS提供的接口请求执行密钥操作,获取操作结果,但无法接触到密钥自身。 + + +**开发步骤** + +生成密钥时使用[huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksgeneratekeyitem9)方法,传入keyAlias作为密钥别名,传入options包含该密钥的属性集,传入callback用于回调异步结果。关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 + + + +1. 确定密钥别名; +2. 初始化密钥属性集:通过[HuksParam](../reference/apis/js-apis-huks.md#huksparam)封装密钥属性,搭配Array组成密钥属性集,并赋值给[HuksOptions](../reference/apis/js-apis-huks.md#huksoptions)(properties字段),其中必须包含[HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg),[HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize),[HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose)属性; +3. 将密钥别名与密钥参数集作为参数传入,生成密钥。 + + > **说明** > -> 本开发指导基于API version 9,仅适用于ArkTS语言开发 - -### **前提条件** +> 存储的 keyAlias 密钥别名最大为64字节 -在使用HUKS的接口开发前,需要引入HUKS模块 +**代码示例:** ```ts -import huks from '@ohos.security.huks' +/* + * 以下以生成DH密钥的Callback操作使用为例 + */ +import huks from '@ohos.security.huks'; + +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let keyAlias = 'dh_key'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_DH +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048 +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} + +/* + * 生成密钥 + */ +function generateKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw (error); + } + }); +} + +async function publicGenKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + try { + await generateKeyItem(keyAlias, huksOptions) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + + +async function TestGenKey() { + await publicGenKeyFunc(keyAlias, huksOptions); +} ``` -### 密钥生成 +## 导入外部密钥 +如果密钥是在HUKS外部生成(比如应用间协商生成、服务器端生成),应用可以将密钥导入到HUKS托管。HUKS支持直接将密钥明文导入到HUKS,但是明文导入会导致密钥暴露在REE内存中,一般适用于轻量级设备或低安业务。对于高安敏感业务,HUKS还提供了安全导入密钥的能力,允许业务自己生成密钥,并通过与处于安全环境中的HUKS建立端到端的加密传输通道,将密钥安全加密导入到HUKS中,确保导入传入过程中密钥不被泄露。 + +与生成密钥一样,密钥一旦导入到HUKS中,密钥的生命周期明文不出安全环境,同样能保证任何人都无法接触获取到密钥的明文。 -通过指定别名和密钥参数的方式,使用HUKS生成应用需要的密钥。生成密钥时支持动态参数指定,分为必选参数和可选参数。其中,必选参数表示在生成密钥时必须传入;可选参数表示在生成密钥时可以传入,也可以不传入。 -> 说明: -> -> 1、生成密钥时传入的参数是对密钥使用的一种约束,规范了密钥使用的范围。如果在使用时传入的参数和生成密钥时传入的参数相悖,则该参数会校验失败。 -> -> 2、如果可选参数没有在生成密钥阶段时传入,但算法又需要该参数,在使用阶段必须传入。 -**支持生成的密钥类型:** +### 明文导入 -这里罗列了密钥生成过程中支持的必选参数,包括密钥算法、密钥长度、密钥用途。详见下文算法的使用过程。 -| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | -| ------------------ | :----------------------------------------------------------- | ------------------------------------------------------------ | -| HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512 HUKS_RSA_KEY_SIZE_768 HUKS_RSA_KEY_SIZE_1024 HUKS_RSA_KEY_SIZE_2048 HUKS_RSA_KEY_SIZE_3072 HUKS_RSA_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT HUKS_KEY_PURPOSE_DERIVE | -| HUKS_ALG_ECC | HUKS_ECC_KEY_SIZE_224 HUKS_ECC_KEY_SIZE_256 HUKS_ECC_KEY_SIZE_384 HUKS_ECC_KEY_SIZE_521 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_X25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_ED25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_DSA | HUKS_RSA_KEY_SIZE_1024 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_DH | HUKS_DH_KEY_SIZE_2048 HUKS_DH_KEY_SIZE_3072 HUKS_DH_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_ECDH | HUKS_ECC_KEY_SIZE_224 HUKS_ECC_KEY_SIZE_256 HUKS_ECC_KEY_SIZE_384 HUKS_ECC_KEY_SIZE_521 | HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_SM2 | HUKS_SM2_KEY_SIZE_256 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_SM4 | HUKS_SM4_KEY_SIZE_128 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | +导入明文密钥时使用[huks.importKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksimportkeyitem9)方法,传入keyAlias作为密钥别名,传入options,其中必须包含密钥材料和密钥属性集,传入callback用于回调异步结果。关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 -在使用示例前,需要先了解几个预先定义的变量: -| 参数名 | 类型 | 必填 | 说明 | -| ---------------- | ----------- | ---- | ------------------------------------------------------------ | -| genKeyAlias | string | 是 | 生成密钥的别名。 | -| genKeyProperties | HuksOptions | 是 | 用于存放生成key所需TAG。其中密钥使用的算法、密钥用途、密钥长度为必选参数。 | +1. 确定密钥别名; +2. 封装密钥材料和密钥属性集:密钥材料须符合[HUKS密钥材料格式](./huks-appendix.md#密钥材料格式)并以Uint8Array形式赋值给[HuksOptions](../reference/apis/js-apis-huks.md#huksoptions)的inData字段;另外,通过[HuksParam](../reference/apis/js-apis-huks.md#huksparam)封装密钥属性,搭配Array组成密钥属性集赋值给properties字段,属性集中必须包含[HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg),[HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize),[HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose)属性; +3. 导入密钥。 + -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 + +**代码示例:** ```ts -/* 以生成ECC256密钥为例 */ -let keyAlias = 'keyAlias'; +/* + * 以导入AES256密钥为例 + */ + +/* 密钥 */ +let plainTextSize32 = new Uint8Array([ + 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca, + 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9 +]); + +/* + * 确定密钥别名 + */ +let keyAlias = 'AES256Alias_sample'; + +/* + * 封装密钥属性集和密钥材料 + */ let properties = new Array(); -//必选参数 properties[0] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC + value: huks.HuksKeyAlg.HUKS_ALG_AES }; -//必选参数 properties[1] = { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; -//必选参数 properties[2] = { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY -}; -//可选参数 -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; let options = { - properties: properties + properties: properties, + inData: plainTextSize32 }; + +/* + * 导入密钥 + */ try { - huks.generateKeyItem(keyAlias, options, function (error, data) { + huks.importKeyItem(keyAlias, options, function (error, data) { if (error) { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); } else { - console.info(`callback: generateKeyItem key success`); + console.info(`callback: importKeyItem success`); } }); } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` + +**调测验证** + +验证时查询密钥是否存在,如密钥存在即表示生成密钥成功。 + +**代码示例:** + +```ts +import huks from '@ohos.security.huks'; + +let keyAlias = 'AES256Alias_sample'; +let isKeyExist; + +let keyProperties = new Array(); +keyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +let huksOptions = { + properties: keyProperties, // 非空填充 + inData: new Uint8Array(new Array()) // 非空填充 +} +try { + huks.isKeyItemExist(keyAlias, huksOptions, function (error, data) { + if (error) { + console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + } 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, code: ${error.code}, msg: ${error.message}`); } ``` +### 加密导入 +相比明文导入,加密导入步骤更多,密钥材料更复杂,此章节将展示开发过程中关键的开发流程和密钥材料数据结构。下图是加密导入的基本开发流程。 -### 密钥导入导出 -HUKS支持非对称密钥的公钥导出能力,开发者可以通过密钥别名导出应用自己密钥对的公钥,只允许导出属于应用自己的密钥对的公钥。 -HUKS支持密钥从外部导入的能力。密钥导入后全生命周期存在HUKS中,不能再被导出(非对称密钥的公钥除外)。 如果该别名的密钥已经存在,新导入的密钥将覆盖已经存在的密钥。 +**图2** 加密导入开发流程 -开发步骤如下: +![huks_import_wrapped_key](figures/huks_import_wrapped_key.png) -1. 生成密钥。 -2. 导出密钥。 -3. 导入密钥。 -**支持导入的密钥类型:** -AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4. -**支持导出的密钥类型:** +**接口说明** -RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2. +根据开发流程,在导入加密密钥过程中,需要依次调用HUKS的生成密钥、导出公钥、导入加密密钥、删除密钥接口。 +| 接口名 | 描述 | +| -------------------------------------- | ----------------------------| +|generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| 生成新密钥| +|exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void| 导出密钥对的公钥| +|importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback) : void|导入加密密钥| +|deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void|删除密钥| -> **说明** -> -> 存储的 keyAlias 密钥别名最大为64字节 +需要注意的是,导出密钥接口返回的公钥明文材料是按照**X.509**格式封装,导入加密密钥接口中的密钥材料需满足**LengthData-Data** 的格式封装。具体,应用需要申请一个Uint8Array按照以下表格中的顺序依次封装。 + +**表2** 加密密钥材料格式 -在使用示例前,需要先了解几个预先定义的变量: +| 内容 | 业务公钥长度Lpk2 | 业务公钥pk2 | k2加密参数AAD2长度LAAD2 | k2加密参数AAD2 | k2加密参数Nonce2长度LNonce2 | k2加密参数Nonce2 | +| :--: |:----:|:----: |:----: | :----: | :----:|:----:| +|长度| 4字节 |Lpk2字节| 4字节 | LAAD2字节 | 4字节 | LNonce2字节 | +| 内容 | k2加密参数AEAD2长度LAEAD2 | k2加密参数AEAD2 | k3密文长度Lk3_enc | k3密文k3_enc | k3加密参数AAD3长度LAAD3 | k3加密参数AAD3 | +|长度| 4字节 |LAEAD2字节| 4字节 | Lk3_enc字节 | 4字节 | LAAD3字节 | +| 内容| k3加密参数Nonce3长度LNonce3 | k3加密参数Nonce3 | k3加密参数AEAD3长度LAEAD3 | k3加密参数AEAD3 | **密钥明文材料长度** 的长度Lk1'_size | 密钥明文材料长度k1'_size | +|长度| 4字节 |LNonce3字节| 4字节 | LAEAD3字节 | 4字节 | Lk1'_size字节 | +|内容|k1'密文长度Lk1'_enc| k1'密文k1'_enc| | | | | +|长度| 4字节 |Lk1'_enc字节| | | | | -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ----------- | ---- | ------------------------ | -| exportKeyAlias | string | 是 | 生成密钥别名。 | -| importKeyAlias | string | 是 | 导入密钥别名。 | -| huksOptions | HuksOptions | 是 | 用于存放生成key所需TAG。 | -| encryptOptions | HuksOptions | 是 | 用于存放导入key所需TAG。 | +**开发步骤** -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 +这里主要展示涉及调用HUKS的开发样例(使用ECDH密钥协商套件),部分在业务本地执行的步骤不在这里展示详细样例。 +1. 转换成HUKS格式的密钥材料 +2. 生成加密导入用途的密钥 +3. 导出公钥材料 +4. 封装加密导入密钥材料 +5. 导入封装的加密密钥材料 +6. 删除用于加密导入的密钥 -**示例:** +**代码示例:** ```ts -/* 以导出RSA512密钥及导入DH2048密钥、RSA512密钥、x25519密钥、ECC256密钥为例 */ +/* + * 以下以SM2密钥的Callback操作验证为例 + */ import huks from '@ohos.security.huks'; -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} +/* + * 确定密钥别名 + */ +let importAlias = "importAlias"; +let wrapAlias = "wrappingKeyAlias"; +let exportKey; -function Uint8ArrayToString(fileData) { - let dataString = ''; - for (let i = 0; i < fileData.length; i++) { - dataString += String.fromCharCode(fileData[i]); - } - return dataString; -} +/* + * 加密导入用途的密钥材料原文:转换成HUKS ECC-P-256密钥对格式的密钥材料 + */ +let inputEccPair = new Uint8Array([ + 0x02, 0x00, 0x00, 0x00, // 密钥算法:huks.HuksKeyAlg.HUKS_ALG_ECC = 2 + 0x00, 0x01, 0x00, 0x00, // 密钥大小(比特):256 + 0x20, 0x00, 0x00, 0x00, // 坐标x长度(字节):32 + 0x20, 0x00, 0x00, 0x00, // 坐标y长度(字节):32 + 0x20, 0x00, 0x00, 0x00, // 坐标z长度(字节):32 + // 坐标x + 0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, 0xcf, 0x60, 0xf6, + 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13, + // 坐标y + 0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, 0xaa, 0xbc, + 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35, + // 坐标z + 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca, + 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9 + ]); -function Uint32ToUint8(value) { - let arr = new Uint8Array(4 * value.length); - for (let i = 0, j = value.length; i < j; i++) { - arr[i * 4+3] = (value[i] >> 24) & 0xFF; - arr[i * 4+2] = (value[i] >> 16) & 0xFF; - arr[i * 4+1] = (value[i] >> 8) & 0xFF; - arr[i*4] = (value[i]) & 0xFF; - } - return arr; -} +/* + * 封装密钥属性参数集 + */ +// 生成加密导入用途的密钥的属性集 +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, + value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, +}; +let huksOptions = { + properties: properties, + inData: inputEccPair +}; -async function publicGenKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} +// 待导入密钥的属性集:AES256 +let importProperties = new Array(); +importProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +importProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 +}; +importProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +importProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC +}; +importProperties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE +}; +importProperties[5] = { + tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, + value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING // 使用“ECDH+AES256GCM”加密导入套件 +}; +let importOptions = { + properties: importProperties, + inData: new Uint8Array(new Array()) +}; -function generateKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { +// 导出加密导入用途的公钥 +function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -188,89 +363,111 @@ function generateKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { } }); } catch (error) { - throw (error); + throwObject.isThrow = true; + throw(error); } }); } -async function publicExportKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { +async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter callback export`); + let throwObject = {isThrow: false}; try { - await exportKeyItem(keyAlias, huksOptions) - .then((data) => { + await exportKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportKey = data.outData; }) .catch(error => { - console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function exportKeyItem(keyAlias: string, huksOptions: huks.HuksOptions): Promise { +// 此处用导入密钥来模拟“生成加密导入用途的密钥” +function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { - huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { + huks.importKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); - } else { + } else { resolve(data); } }); } catch (error) { - throw (error); + throwObject.isThrow = true; + throw(error); } }); } -async function publicImportKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { +async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter promise importKeyItem`); + let throwObject = {isThrow: false}; try { - await importKeyItem(keyAlias, huksOptions) - .then((data) => { + await importKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function importKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { +// 执行加密导入 +async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback importWrappedKeyItem`); + var throwObject = {isThrow: false}; + try { + await importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: importWrappedKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { - huks.importKeyItem(keyAlias, huksOptions, function (error, data) { + huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { - resolve(data); + resolve(data); } }); } catch (error) { - throw (error); + throwObject.isThrow = true; + throw(error); } }); } -async function publicDeleteKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - try { - await deleteKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { +// 删除加密导入用途的密钥 +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { @@ -281,549 +478,314 @@ function deleteKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { } }); } catch (error) { - throw (error); + throwObject.isThrow = true; + throw(error); } }); } -//导出RSA密钥 -async function testExportRsa() { - let exportKeyAlias = 'export_rsa_key'; - /* 集成生成密钥参数集 */ - let exportProperties = new Array(); - exportProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - } - exportProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT - } - exportProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 - } - exportProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - } - exportProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 - } - exportProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - let huksOptions = { - properties: exportProperties, - inData: new Uint8Array(new Array()) +async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback deleteKeyItem`); + let throwObject = {isThrow: false}; + try { + await deleteKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } +} - /* 生成密钥 */ - await publicGenKeyFunc(exportKeyAlias, huksOptions); +async function ImportWrappedKeyNormalTest() { + console.info(`enter ImportWrapKey test`); + /* + * 生成加密导入用途的密钥(此处使用导入进行模拟) + */ + await publicImportKeyFunc(wrapAlias, huksOptions); - /* 导出密钥 */ - await publicExportKeyFunc(exportKeyAlias, huksOptions); - await publicDeleteKeyFunc(exportKeyAlias, huksOptions); -} - -//DH密钥 -let g_dhPubData = new Uint8Array([ - 0x8a, 0xbf, 0x16, 0x67, 0x1b, 0x92, 0x4b, 0xf2, 0xe0, 0x02, 0xc5, 0x1f, 0x84, 0x00, 0xf8, 0x93, - 0x0f, 0x74, 0xe7, 0x0f, 0xba, 0x78, 0x30, 0xa8, 0x2d, 0x92, 0xef, 0x9b, 0x80, 0xeb, 0x76, 0xea, - 0x26, 0x74, 0x72, 0x63, 0x6a, 0x27, 0xc3, 0x8f, 0xcf, 0xbe, 0x82, 0xa2, 0x8b, 0xdc, 0x65, 0x58, - 0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, - 0x48, 0xb3, 0x6b, 0x7a, 0xce, 0x2e, 0x81, 0x3d, 0x38, 0x35, 0x59, 0xdc, 0x39, 0x8a, 0x97, 0xfe, - 0x20, 0x86, 0x20, 0xdb, 0x55, 0x38, 0x23, 0xca, 0xb5, 0x5b, 0x61, 0x00, 0xdc, 0x45, 0xe2, 0xa1, - 0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x66, 0x73, - 0x4e, 0xaf, 0xee, 0xb0, 0xb0, 0x69, 0x0c, 0x13, 0xba, 0x76, 0xff, 0x2e, 0xb6, 0x16, 0xf9, 0xfc, - 0xd6, 0x09, 0x5b, 0xc7, 0x37, 0x65, 0x84, 0xd5, 0x82, 0x8a, 0xd7, 0x5b, 0x57, 0xe3, 0x0e, 0x89, - 0xbe, 0x05, 0x05, 0x55, 0x2e, 0x9f, 0x94, 0x8a, 0x53, 0xdc, 0xb7, 0x00, 0xb2, 0x6a, 0x7b, 0x8e, - 0xdf, 0x6e, 0xa4, 0x6d, 0x13, 0xb6, 0xbc, 0xaa, 0x8e, 0x44, 0x11, 0x50, 0x32, 0x91, 0x56, 0xa2, - 0x22, 0x3f, 0x2f, 0x08, 0xbb, 0x4d, 0xbb, 0x69, 0xe6, 0xb1, 0xc2, 0x70, 0x79, 0x15, 0x54, 0xad, - 0x4a, 0x29, 0xef, 0xa9, 0x3e, 0x64, 0x8d, 0xf1, 0x90, 0xf4, 0xa7, 0x93, 0x8c, 0x7a, 0x02, 0x4d, - 0x38, 0x1f, 0x58, 0xb8, 0xe4, 0x7c, 0xe1, 0x66, 0x1c, 0x72, 0x30, 0xf3, 0x4c, 0xf4, 0x24, 0xd1, - 0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, - 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, 0x9c, 0xc8, 0xb7]); -let g_dhPriData = new Uint8Array([ - 0x01, 0xbc, 0xa7, 0x42, 0x25, 0x79, 0xc5, 0xaf, 0x0f, 0x9c, 0xde, 0x00, 0x3b, 0x58, 0x5c, 0xd1, - 0x1d, 0x7b, 0xcf, 0x66, 0xcd, 0xa9, 0x10, 0xae, 0x92, 0x2d, 0x3c, 0xb7, 0xf3]); -let g_dhX509PubData = new Uint8Array([ - 0x30, 0x82, 0x02, 0x29, 0x30, 0x82, 0x01, 0x1b, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, - 0x01, 0x03, 0x01, 0x30, 0x82, 0x01, 0x0c, 0x02, 0x82, 0x01, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xad, 0xf8, 0x54, 0x58, 0xa2, 0xbb, 0x4a, 0x9a, 0xaf, 0xdc, 0x56, 0x20, - 0x27, 0x3d, 0x3c, 0xf1, 0xd8, 0xb9, 0xc5, 0x83, 0xce, 0x2d, 0x36, 0x95, 0xa9, 0xe1, 0x36, 0x41, - 0x14, 0x64, 0x33, 0xfb, 0xcc, 0x93, 0x9d, 0xce, 0x24, 0x9b, 0x3e, 0xf9, 0x7d, 0x2f, 0xe3, 0x63, - 0x63, 0x0c, 0x75, 0xd8, 0xf6, 0x81, 0xb2, 0x02, 0xae, 0xc4, 0x61, 0x7a, 0xd3, 0xdf, 0x1e, 0xd5, - 0xd5, 0xfd, 0x65, 0x61, 0x24, 0x33, 0xf5, 0x1f, 0x5f, 0x06, 0x6e, 0xd0, 0x85, 0x63, 0x65, 0x55, - 0x3d, 0xed, 0x1a, 0xf3, 0xb5, 0x57, 0x13, 0x5e, 0x7f, 0x57, 0xc9, 0x35, 0x98, 0x4f, 0x0c, 0x70, - 0xe0, 0xe6, 0x8b, 0x77, 0xe2, 0xa6, 0x89, 0xda, 0xf3, 0xef, 0xe8, 0x72, 0x1d, 0xf1, 0x58, 0xa1, - 0x36, 0xad, 0xe7, 0x35, 0x30, 0xac, 0xca, 0x4f, 0x48, 0x3a, 0x79, 0x7a, 0xbc, 0x0a, 0xb1, 0x82, - 0xb3, 0x24, 0xfb, 0x61, 0xd1, 0x08, 0xa9, 0x4b, 0xb2, 0xc8, 0xe3, 0xfb, 0xb9, 0x6a, 0xda, 0xb7, - 0x60, 0xd7, 0xf4, 0x68, 0x1d, 0x4f, 0x42, 0xa3, 0xde, 0x39, 0x4d, 0xf4, 0xae, 0x56, 0xed, 0xe7, - 0x63, 0x72, 0xbb, 0x19, 0x0b, 0x07, 0xa7, 0xc8, 0xee, 0x0a, 0x6d, 0x70, 0x9e, 0x02, 0xfc, 0xe1, - 0xcd, 0xf7, 0xe2, 0xec, 0xc0, 0x34, 0x04, 0xcd, 0x28, 0x34, 0x2f, 0x61, 0x91, 0x72, 0xfe, 0x9c, - 0xe9, 0x85, 0x83, 0xff, 0x8e, 0x4f, 0x12, 0x32, 0xee, 0xf2, 0x81, 0x83, 0xc3, 0xfe, 0x3b, 0x1b, - 0x4c, 0x6f, 0xad, 0x73, 0x3b, 0xb5, 0xfc, 0xbc, 0x2e, 0xc2, 0x20, 0x05, 0xc5, 0x8e, 0xf1, 0x83, - 0x7d, 0x16, 0x83, 0xb2, 0xc6, 0xf3, 0x4a, 0x26, 0xc1, 0xb2, 0xef, 0xfa, 0x88, 0x6b, 0x42, 0x38, - 0x61, 0x28, 0x5c, 0x97, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x01, 0x02, 0x02, - 0x02, 0x00, 0xe1, 0x03, 0x82, 0x01, 0x06, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0x8a, 0xbf, 0x16, - 0x67, 0x1b, 0x92, 0x4b, 0xf2, 0xe0, 0x02, 0xc5, 0x1f, 0x84, 0x00, 0xf8, 0x93, 0x0f, 0x74, 0xe7, - 0x0f, 0xba, 0x78, 0x30, 0xa8, 0x2d, 0x92, 0xef, 0x9b, 0x80, 0xeb, 0x76, 0xea, 0x26, 0x74, 0x72, - 0x63, 0x6a, 0x27, 0xc3, 0x8f, 0xcf, 0xbe, 0x82, 0xa2, 0x8b, 0xdc, 0x65, 0x58, 0xe3, 0xff, 0x29, - 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, 0x48, 0xb3, 0x6b, - 0x7a, 0xce, 0x2e, 0x81, 0x3d, 0x38, 0x35, 0x59, 0xdc, 0x39, 0x8a, 0x97, 0xfe, 0x20, 0x86, 0x20, - 0xdb, 0x55, 0x38, 0x23, 0xca, 0xb5, 0x5b, 0x61, 0x00, 0xdc, 0x45, 0xe2, 0xa1, 0xf4, 0x1e, 0x7b, - 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x66, 0x73, 0x4e, 0xaf, 0xee, - 0xb0, 0xb0, 0x69, 0x0c, 0x13, 0xba, 0x76, 0xff, 0x2e, 0xb6, 0x16, 0xf9, 0xfc, 0xd6, 0x09, 0x5b, - 0xc7, 0x37, 0x65, 0x84, 0xd5, 0x82, 0x8a, 0xd7, 0x5b, 0x57, 0xe3, 0x0e, 0x89, 0xbe, 0x05, 0x05, - 0x55, 0x2e, 0x9f, 0x94, 0x8a, 0x53, 0xdc, 0xb7, 0x00, 0xb2, 0x6a, 0x7b, 0x8e, 0xdf, 0x6e, 0xa4, - 0x6d, 0x13, 0xb6, 0xbc, 0xaa, 0x8e, 0x44, 0x11, 0x50, 0x32, 0x91, 0x56, 0xa2, 0x22, 0x3f, 0x2f, - 0x08, 0xbb, 0x4d, 0xbb, 0x69, 0xe6, 0xb1, 0xc2, 0x70, 0x79, 0x15, 0x54, 0xad, 0x4a, 0x29, 0xef, - 0xa9, 0x3e, 0x64, 0x8d, 0xf1, 0x90, 0xf4, 0xa7, 0x93, 0x8c, 0x7a, 0x02, 0x4d, 0x38, 0x1f, 0x58, - 0xb8, 0xe4, 0x7c, 0xe1, 0x66, 0x1c, 0x72, 0x30, 0xf3, 0x4c, 0xf4, 0x24, 0xd1, 0x2d, 0xb7, 0xf1, - 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, 0xbf, 0xf9, 0x69, - 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, 0x9c, 0xc8, 0xb7]); - -//x25519秘钥 -let g_x25519PubData = new Uint8Array([ - 0x9c, 0xf6, 0x7a, 0x8d, 0xce, 0xc2, 0x7f, 0xa7, 0xd9, 0xfd, 0xf1, 0xad, 0xac, 0xf0, 0xb3, 0x8c, - 0xe8, 0x16, 0xa2, 0x65, 0xcc, 0x18, 0x55, 0x60, 0xcd, 0x2f, 0xf5, 0xe5, 0x72, 0xc9, 0x3c, 0x54]); -//x25519公钥 -let g_x25519PriData = new Uint8Array([ - 0x20, 0xd5, 0xbb, 0x54, 0x6f, 0x1f, 0x00, 0x30, 0x4e, 0x33, 0x38, 0xb9, 0x8e, 0x6a, 0xdf, 0xad, - 0x33, 0x6f, 0x51, 0x23, 0xff, 0x4d, 0x95, 0x26, 0xdc, 0xb0, 0x74, 0xb2, 0x5c, 0x7e, 0x85, 0x6c]); - -//rsa密钥 -let g_nData = new Uint8Array([ - 0xb6, 0xd8, 0x9b, 0x33, 0x78, 0xa2, 0x63, 0x21, 0x84, 0x47, 0xa1, 0x72, 0 x3d, 0x73, 0x10, 0xbd, - 0xe9, 0x5d, 0x78, 0x44, 0x3d, 0x80, 0x18, 0x12, 0x60, 0xed, 0x29, 0x3e, 0xc7, 0x23, 0x0d, 0x3f, - 0x02, 0x59, 0x28, 0xe2, 0x8f, 0x83, 0xdf, 0x37, 0x4b, 0x77, 0xce, 0x5f, 0xb6, 0xcd, 0x61, 0x72, - 0xee, 0x01, 0xe2, 0x37, 0x4d, 0xfd, 0x4f, 0x39, 0xcf, 0xbd, 0xff, 0x84, 0x57, 0x44, 0xa5, 0x03]); -let g_eData = new Uint8Array([0x01, 0x00, 0x01]); -let g_dData = new Uint8Array([ - 0x35, 0x63, 0x89, 0xed, 0xbd, 0x8b, 0xac, 0xe6, 0x5c, 0x79, 0x8d, 0xea, 0x8d, 0x86, 0xcb, 0x9c, - 0xa8, 0x47, 0x62, 0x96, 0x8a, 0x5e, 0x9c, 0xa8, 0xc1, 0x24, 0x7e, 0xa6, 0x95, 0xfe, 0xe6, 0x1e, - 0xc0, 0xf3, 0x29, 0x76, 0xbb, 0x4d, 0xe4, 0xbc, 0x78, 0x64, 0xe1, 0x79, 0xcd, 0x8a, 0x45, 0xac, - 0x5c, 0x88, 0xea, 0xb4, 0x10, 0xd8, 0x90, 0x65, 0x7b, 0x94, 0xe8, 0x87, 0x30, 0x2a, 0x04, 0x01]); -let g_pubData = new Uint8Array([ - 0x30, 0x5c, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, - 0x00, 0x03, 0x4b, 0x00, 0x30, 0x48, 0x02, 0x41, 0x00, 0x9e, 0x93, 0x57, 0xc4, 0xab, 0xde, 0x30, - 0xc5, 0x3f, 0x3b, 0x33, 0xa6, 0xdc, 0x4a, 0xdb, 0xbf, 0x12, 0x9e, 0x5d, 0xc4, 0xba, 0x0e, 0x15, - 0x06, 0x41, 0xd8, 0x96, 0x43, 0xca, 0xc5, 0xea, 0x9f, 0xdd, 0xa0, 0x2a, 0xf1, 0x53, 0x46, 0x14, - 0x36, 0x7a, 0xab, 0xbc, 0x92, 0x1b, 0x07, 0xc6, 0x9a, 0x7d, 0x0c, 0xd0, 0xa0, 0x0f, 0x31, 0xd5, - 0x38, 0x84, 0x6c, 0x08, 0xcb, 0x9b, 0x10, 0xa6, 0x4d, 0x02, 0x03, 0x01, 0x00, 0x01]); - -//ecc密钥 -let g_eccXData = new Uint8Array([ - 0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, 0xcf, 0x60, 0xf6, - 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13]); -let g_eccYData = new Uint8Array([ - 0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, 0xaa, 0xbc, - 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35]); -let g_eccZData = new Uint8Array([ - 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca, - 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9]); -let g_eccPubData = new Uint8Array([ - 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, - 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xa5, 0xb8, 0xa3, 0x78, 0x1d, - 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, 0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, - 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, 0x2a, 0xb5, - 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, 0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, - 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35]); - -//导入DH2048密钥 -async function ImportDhTest(alg, keyType) { - let importKeyAlias = 'import_dh_key'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_DH - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048 - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - huksOptions.properties[0].value = alg; - huksOptions.properties[3].value = keyType; - - //对比密钥类型 - if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) { - /* 非公钥拼接huksOptions.inData字段,满足以下格式: - * keyAlg的类型(4字节) + key_dh的长度(4字节) + - * g_dhPubData的长度(4字节) + g_dhPriData的长度(4字节) + - * reserved的大小(4字节) + g_dhPubData的数据 + g_dhPriData的数据 - */ - // PAIR - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_DH, huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048, g_dhPubData.length, g_dhPriData.length, 0]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - - let strXData = strMaterial.concat(Uint8ArrayToString(g_dhPubData)); - let strData = strXData.concat(Uint8ArrayToString(g_dhPriData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) { - //私钥 - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_DH, huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048, 0, g_dhPriData.length, 0]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - - let strData = strMaterial.concat(Uint8ArrayToString(g_dhPriData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) { - //公钥 - huksOptions.inData = g_dhX509PubData; - } + /* + * 导出加密导入用途密钥的公钥材料 + */ + await publicExportKeyFunc(wrapAlias, huksOptions); - await publicImportKeyFunc(importKeyAlias, huksOptions); - await publicDeleteKeyFunc(importKeyAlias, huksOptions); -} + /*---------------------------------------------------------------------------------------------- + * 此处省略业务本地生成ECC密钥对、业务本地ECDH密钥协商、业务本地生成密钥加密密钥K3、业务本地加密K1'和K3的流程 + *----------------------------------------------------------------------------------------------*/ + + /* 封装加密导入密钥材料:参考加密导入 + * 拼接importOptions.inData字段,满足以下格式: + * PK2长度(4字节) + PK2的数据 + AAD2的长度(4字节) + AAD2的数据 + + * Nonce2的长度(4字节)+ Nonce2的数据 + AEAD2的长度(4字节) + AEAD2的数据 + + * K3密文的长度(4字节) + K3密文的数据 + AAD3的长度(4字节) + AAD3的数据 + + * Nonce3的长度(4字节) + Nonce3的数据 + AEAD3的长度(4字节) + AEAD3的数据 + + * K1'_size的长度(4字节) + K1'_size + K1'_enc的长度(4字节) + K1'_enc的数据 + */ + let inputKey = new Uint8Array([ + 0x5b, 0x00, 0x00, 0x00, // ECC-P-256 公钥长度(X.509规范DER格式):91 + // ECC-P-256 公钥 + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, + 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe, 0x1c, 0x67, 0xde, + 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2, + 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99, 0x3d, 0xe8, + 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44, + 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, + + 0x10, 0x00, 0x00, 0x00, // AAD2长度:16 + // AAD2 + 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, 0x9c, 0xc8, 0xb7, + + 0x10, 0x00, 0x00, 0x00, // Nonce2长度:16 + // Nonce2 + 0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, + + 0x10, 0x00, 0x00, 0x00, // AEAD2长度:16 + // AEAD2 + 0x43, 0x25, 0x1b, 0x2f, 0x5b, 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e, 0xb7, + + 0x20, 0x00, 0x00, 0x00, // K3密文长度:32 + // K3密文 + 0xf4, 0xe8, 0x93, 0x28, 0x0c, 0xfa, 0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, + 0x2f, 0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d, 0x19, 0x26, 0x09, 0xe7, + + 0x10, 0x00, 0x00, 0x00, // AAD3长度:16 + // AAD3 + 0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x66, 0x73, + + 0x10, 0x00, 0x00, 0x00, // Nonce3长度:16 + // Nonce3 + 0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, + + 0x10, 0x00, 0x00, 0x00, // AEAD3长度:16 + // AEAD3 + 0x26, 0xae, 0xdc, 0x4e, 0xa5, 0x6e, 0xb1, 0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11, + + 0x04, 0x00, 0x00, 0x00, // “密钥明文材料长度”的长度(字节):4 + // 密钥明文材料的长度:32字节 + 0x20, 0x00, 0x00, 0x00, + + 0x20, 0x00, 0x00, 0x00, // 待导入密钥密文长度(字节):32 + // 待导入密钥密文 + 0x0b, 0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1, 0xfc, 0x72, 0x74, 0x87, 0x79, 0xf2, 0xf4, + 0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10, 0xc8, 0x44, 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a + ]); + importOptions.inData = inputKey; -//导入ecc256密钥 -async function ImportEccTest(alg, keyType) { - let importKeyAlias = 'import_ecc_key'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - huksOptions.properties[0].value = alg; - huksOptions.properties[3].value = keyType; - - //对比密钥类型 - if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) { - /* 非公钥拼接huksOptions.inData字段,满足以下格式: - * keyAlg的类型(4字节) + key_ecc的长度(4字节) + - * g_eccXData的长度(4字节) + g_eccYData的长度(4字节) + - * g_eccZData的长度(4字节) + g_eccXData的数据 + - * g_eccYData的数据 + g_eccZData的数据 - */ - //PAIR - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_ECC, huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256, g_eccXData.length, g_eccYData.length, g_eccZData.length]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - - let strXData = strMaterial.concat(Uint8ArrayToString(g_eccXData)); - let strYData = strXData.concat(Uint8ArrayToString(g_eccYData)); - let strData = strYData.concat(Uint8ArrayToString(g_eccZData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) { - //私钥 - huksOptions.properties[3].value == huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_ECC, huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256, 0, 0, g_eccZData.length]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - - let strData = strMaterial.concat(Uint8ArrayToString(g_eccZData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) { - //公钥 - huksOptions.inData = g_eccPubData; - } + /* + * 导入封装的加密密钥材料 + */ + await publicImportWrappedKey(importAlias, wrapAlias, importOptions); - await publicImportKeyFunc(importKeyAlias, huksOptions); - await publicDeleteKeyFunc(importKeyAlias, huksOptions); + /* + * 删除用于加密导入的密钥 + */ + await publicDeleteKeyFunc(wrapAlias, huksOptions); } +``` -//导入rsa512密钥 -async function ImportRsaTest(alg, keyType) { - let importKeyAlias = 'import_rsa_key'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 - } - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - huksOptions.properties[0].value = alg; - huksOptions.properties[3].value = keyType; - - //对比密钥类型 - if (huksOptions.properties[5].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) { - /* 非公钥拼接huksOptions.inData字段,满足以下格式: - * keyAlg的类型(4字节) + key_rsa的长度(4字节) + - * g_nData的长度(4字节) + g_eData的长度(4字节) + - * g_dData的长度(4字节) + g_nData的数据 + - * g_eData的数据 + g_dData的数据 - */ - //PAIR - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_RSA, huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, g_nData.length, g_eData.length, g_dData.length]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - let strNData = strMaterial.concat(Uint8ArrayToString(g_nData)); - let strEData = strNData.concat(Uint8ArrayToString(g_eData)); - let strData = strEData.concat(Uint8ArrayToString(g_dData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[5].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) { - //私钥 - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_RSA, huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, g_nData.length, 0, g_dData.length]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - let strNData = strMaterial.concat(Uint8ArrayToString(g_nData)); - let strData = strNData.concat(Uint8ArrayToString(g_dData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[5].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) { - //公钥 - huksOptions.inData = g_pubData; - } - await publicImportKeyFunc(importKeyAlias, huksOptions); - await publicDeleteKeyFunc(importKeyAlias, huksOptions); -} +**调测验证** -//导入x25519密钥 -async function ImportX25519Test(alg, keyType) { - let importKeyAlias = 'import_x25519_key'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_X25519 - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256 - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - huksOptions.properties[0].value = alg; - huksOptions.properties[3].value = keyType; - - //对比密钥类型 - if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) { - /* 非公钥拼接huksOptions.inData字段,满足以下格式: - * keyAlg的类型(4字节) + key_x25519的长度(4字节) + - * g_x25519PubData的长度(4字节) + g_x25519PriData的长度(4字节) + - * reserved的大小(4字节) + g_x25519PubData的数据 + - * g_x25519PriData的数据 - */ - //PAIR - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_X25519, huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256, g_x25519PriData.length, g_x25519PubData.length, 0]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - let strXData = strMaterial.concat(Uint8ArrayToString(g_x25519PubData)); - let strData = strXData.concat(Uint8ArrayToString(g_x25519PriData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) { - //私钥 - huksOptions.inData = g_x25519PriData; - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) { - //公钥 - huksOptions.inData = g_x25519PubData; - } - await publicImportKeyFunc(importKeyAlias, huksOptions); - await publicDeleteKeyFunc(importKeyAlias, huksOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testExportRsa') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - testExportRsa(); - }) +验证时查询密钥是否存在,如密钥存在即表示生成密钥成功。 - Button() { - Text('testImportDh') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - ImportDhTest(huks.HuksKeyAlg.HUKS_ALG_DH, huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY); - }) +**代码示例:** - Button() { - Text('testImportRsa') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - ImportRsaTest(huks.HuksKeyAlg.HUKS_ALG_RSA, huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR); - }) +```ts +import huks from '@ohos.security.huks'; - Button() { - Text('testImportX25519') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - ImportX25519Test(huks.HuksKeyAlg.HUKS_ALG_X25519, huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY); - }) +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let keyAlias = 'importAlias'; +let isKeyExist; - Button() { - Text('testImportEcc') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - ImportEccTest(huks.HuksKeyAlg.HUKS_ALG_ECC, huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY); - }) +let keyProperties = new Array(); +keyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +let huksOptions = { + properties: keyProperties, // 非空填充 + inData: new Uint8Array(new Array()) // 非空填充 +} +try { + huks.isKeyItemExist(keyAlias, huksOptions, function (error, data) { + if (error) { + console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + } else { + if (data !== null && data.valueOf() !== null) { + isKeyExist = data.valueOf(); + console.info(`callback: isKeyItemExist success, isKeyExist = ${isKeyExist}`); + } } - .width('100%') - .height('100%') - } + }); +} catch (error) { + console.error(`callback: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } ``` -### 安全导入 -基于密钥协商和中间密钥二次加密的方式,业务调用方和HUKS各自协商出共享的对称密钥来对中间密钥、待导入密钥进行加解密。从而实现密文导入后,在HUKS中对导入密钥进行解密再保存。对明文密钥的处理仅在HUKS 安全环境中,保证密钥明文生命周期内不出安全环境。 +## 常见密钥操作 -开发步骤如下: +**场景概述** -1. huks中生成用于加密导入协商的密钥。 -2. 导出该密钥的公钥,协商出共享密钥。 -3. 生成中间密钥材料并加密密钥。 -4. 导入密钥。 +为了实现对数据机密性、完整性等保护,在生成/导入密钥后,需要对数据进行密钥操作,比如加密解密、签名验签、密钥协商、密钥派生等,本章节提供了常用的密钥操作的示例。本章节提供的示例都没有设置二次身份访问控制,如设置了密钥访问控制请参考[密钥访问控制](#密钥访问控制)用法。 -**支持的密钥类型:** +**通用开发流程** -AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4. +HUKS基于密钥会话来操作数据,使用密钥时基于以下流程: +1. **初始化密钥会话[huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9):** 传入密钥别名和密钥操作参数,初始化一个密钥会话并获取会话句柄。其中密钥操作参数中必须包含对应密码算法所必须的参数,包括密码算法、密钥大小、密钥目的、工作模式、填充模式、散列模式、IV、Nonce、AAD等。如果密钥设置了访问控制属性,还需要其他参数具体[密钥访问控制](#密钥访问控制)。此步骤必选! +2. **分段操作数据[huks.updateSession()](../reference/apis/js-apis-huks.md#huksupdatesession9):** 如数据过大(超过100K)或密码算法的要求需要对数据进行分段操作,反之可跳过此步。此步骤可选! +3. **结束密钥会话[huks.finishSession()](../reference/apis/js-apis-huks.md#huksfinishsession9):** 操作最后一段数据并结束密钥会话,如过程中发生错误或不需要此次密钥操作数据,必须取消会话[huks.abortSession()](../reference/apis/js-apis-huks.md#huksabortsession9)。此步骤必选! -> **注意** -> -> - 生成公共密钥时,要设置参数HUKS_TAG_PURPOSE = HUKS_KEY_PURPOSE_UNWRAP -> - 参数HUKS_TAG_IMPORT_KEY_TYPE = HUKS_KEY_TYPE_KEY_PAIR -> - 安全导入密钥时,参数集须加上参数HUKS_TAG_UNWRAP_ALGORITHM_SUITE, 值为HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING或者HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING -> - 存储的 keyAlias 密钥别名最大为64字节 +### 加密解密 +```ts +/* + * 以下以SM4 128密钥的Callback操作使用为例 + */ +import huks from '@ohos.security.huks'; + +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let srcKeyAlias = 'sm4_Key'; +let IV = '0000000000000000'; +let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; +let encryptUpdateResult = new Array(); +let handle; +let updateResult = new Array(); +let finishOutData; + +/* 集成生成密钥参数集 & 加密参数集 */ +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} -在使用示例前,需要先了解几个预先定义的变量: +let propertiesEncrypt = new Array(); +propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, +} +propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), +} +let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) +} -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ----------- | ---- | -------------------------------- | -| importAlias | string | 是 | 密钥别名。 | -| wrapAlias | string | 是 | 密钥别名。 | -| genWrapOptions | HuksOptions | 是 | 用于存放生成加密协商key所需TAG。 | -| importOptions | HuksOptions | 是 | 用于存放导入加密key所需TAG。 | +/* 修改加密参数集为解密参数集 */ +propertiesEncrypt.splice(1, 1, { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +}); +let decryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) +} -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 +function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} -**示例:** +function Uint8ArrayToString(fileData) { + let dataString = ''; + for (let i = 0; i < fileData.length; i++) { + dataString += String.fromCharCode(fileData[i]); + } + return dataString; +} -```ts -import huks from '@ohos.security.huks'; +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} -async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback export`); +async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await exportKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); - if (data.outData !== null) { - exportKey = data.outData; - } + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { + huks.initSession(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -831,30 +793,37 @@ function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise< } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise importKeyItem`); +async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; try { - await importKeyItem(keyAlias, huksOptions) + await initSession(keyAlias, huksOptions, throwObject) .then ((data) => { - console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`); + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; }) - .catch(error => { - console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.importKeyItem(keyAlias, huksOptions, function (error, data) { + huks.updateSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -862,30 +831,36 @@ function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback importWrappedKeyItem`); +async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { + console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; try { - await importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions) + await updateSession(handle, huksOptions, throwObject) .then ((data) => { - console.info(`callback: importWrappedKeyItem success, data = ${JSON.stringify(data)}`); + console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) { +function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) { + huks.finishSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -893,27 +868,34 @@ function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOpti } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); +async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; try { - await deleteKeyItem(keyAlias, huksOptions) + await finishSession(handle, huksOptions, throwObject) .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { @@ -924,206 +906,157 @@ function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -let importAlias = "importAlias"; -let wrapAlias = "wrappingKeyAlias"; -let exportKey; +async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback deleteKeyItem`); + let throwObject = {isThrow: false}; + try { + await deleteKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} -let inputEccPair = new Uint8Array([ - 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, - 0x20, 0x00, 0x00, 0x00, 0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, - 0x9d, 0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, - 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, - 0x10, 0xf0, 0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, - 0xad, 0xee, 0x34, 0x35, 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, - 0x7c, 0x86, 0xba, 0xca, 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, - 0x9e, 0x3c, 0xe5, 0xf9]); +async function testSm4Cipher() { + /* 生成密钥 */ + await publicGenKeyFunc(srcKeyAlias, huksOptions); -let properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, -}; -let huksOptions = { - properties: properties, - inData: inputEccPair -}; - -let importProperties = new Array(); -importProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -importProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 -}; -importProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -importProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC -}; -importProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE -}; -importProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, - value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING -}; -let importOptions = { - properties: importProperties, - inData: new Uint8Array(new Array()) -}; - -async function importWrappedKeyItemTest() { + /* 进行密钥加密操作 */ + await publicInitFunc(srcKeyAlias, encryptOptions); - console.info(`enter ImportWrapKey test`); - await publicImportKeyFunc(wrapAlias, huksOptions); + encryptOptions.inData = StringToUint8Array(cipherInData); + await publicUpdateFunc(handle, encryptOptions); + encryptUpdateResult = updateResult; - await publicExportKeyFunc(wrapAlias, huksOptions); + encryptOptions.inData = new Uint8Array(new Array()); + await publicFinishFunc(handle, encryptOptions); + if (finishOutData === cipherInData) { + console.info('test finish encrypt err '); + } else { + console.info('test finish encrypt success'); + } - /* 以下操作不需要调用HUKS接口,此处不给出具体实现。 - * 假设待导入的密钥为keyA - * 1.生成ECC公私钥keyB,公钥为keyB_pub, 私钥为keyB_pri - * 2.使用keyB_pri和wrappingAlias密钥中获取的公钥进行密钥协商,协商出共享密钥share_key - * 3.随机生成密钥kek,用于加密keyA,采用AES-GCM加密,加密过程中需要记录:nonce1/aad1/加密后的密文keyA_enc/加密后的tag1。 - * 4.使用share_key加密kek,采用AES-GCM加密,加密过程中需要记录:nonce2/aad2/加密后的密文kek_enc/加密后的tag2。 - * 5.拼接importOptions.inData字段,满足以下格式: - * keyB_pub的长度(4字节) + keyB_pub的数据 + aad2的长度(4字节) + aad2的数据 + - * nonce2的长度(4字节) + nonce2的数据 + tag2的长度(4字节) + tag2的数据 + - * kek_enc的长度(4字节) + kek_enc的数据 + aad1的长度(4字节) + aad1的数据 + - * nonce1的长度(4字节) + nonce1的数据 + tag1的长度(4字节) + tag1的数据 + - * keyA长度占用的内存长度(4字节) + keyA的长度 + keyA_enc的长度(4字节) + keyA_enc的数据 - */ - let inputKey = new Uint8Array([ - 0x5b, 0x00, 0x00, 0x00, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, - 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, - 0xfe, 0x1c, 0x67, 0xde, 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, - 0xaa, 0xc5, 0xd9, 0xd2, 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, - 0xac, 0x99, 0x3d, 0xe8, 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, - 0x7a, 0x41, 0xe5, 0x44, 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, 0x10, - 0x00, 0x00, 0x00, 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, - 0x9c, 0xc8, 0xb7, 0x10, 0x00, 0x00, 0x00, 0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, - 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, 0x10, 0x00, 0x00, 0x00, 0x43, 0x25, 0x1b, 0x2f, 0x5b, - 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e, 0xb7, 0x20, 0x00, 0x00, 0x00, 0xf4, - 0xe8, 0x93, 0x28, 0x0c, 0xfa, 0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, 0x2f, - 0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d, 0x19, 0x26, 0x09, 0xe7, 0x10, - 0x00, 0x00, 0x00, 0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, - 0x57, 0x66, 0x73, 0x10, 0x00, 0x00, 0x00, 0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, - 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, 0x10, 0x00, 0x00, 0x00, 0x26, 0xae, 0xdc, 0x4e, 0xa5, - 0x6e, 0xb1, 0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11, 0x04, 0x00, 0x00, 0x00, 0x20, - 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x0b, 0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1, - 0xfc, 0x72, 0x74, 0x87, 0x79, 0xf2, 0xf4, 0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10, 0xc8, 0x44, - 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a - ]); + /* 进行解密操作 */ + await publicInitFunc(srcKeyAlias, decryptOptions); - importOptions.inData = inputKey; - await publicImportWrappedKey(importAlias, wrapAlias, importOptions); + decryptOptions.inData = new Uint8Array(encryptUpdateResult); + await publicUpdateFunc(handle, decryptOptions); - await publicDeleteKeyFunc(wrapAlias, huksOptions); - await publicDeleteKeyFunc(importAlias, importOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('importWrappedKeyItemTest') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - importWrappedKeyItemTest(); - }) - } - .width('100%') - .height('100%') + decryptOptions.inData = new Uint8Array(new Array()); + await publicFinishFunc(handle, decryptOptions); + if (finishOutData === cipherInData) { + console.info('test finish decrypt success '); + } else { + console.info('test finish decrypt err'); } + + await publicDeleteKeyFunc(srcKeyAlias, huksOptions); } ``` -### 密钥加解密 - -通过指定别名的方式,使用HUKS中存储的对称或非对称密钥对数据进行加密或解密运算,运算过程中密钥明文不出安全环境。 - -开发步骤如下: - -1. 生成密钥。 -2. 密钥加密。 -3. 密钥解密。 - -**支持的密钥类型:** - -| HUKS_ALG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | HUKS_TAG_IV | -| ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------- | ----------- | -| HUKS_ALG_SM4 (支持长度: HUKS_SM4_KEY_SIZE_128) | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | 【非必选】 | HUKS_PADDING_NONE | HUKS_MODE_CTR HUKS_MODE_ECB HUKS_MODE_CBC | 【必选】 | -| HUKS_ALG_SM4 (支持长度: HUKS_SM4_KEY_SIZE_128) | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | 【非必选】 | HUKS_PADDING_PKCS7 | HUKS_MODE_ECB HUKS_MODE_CBC | 【必选】 | -| HUKS_ALG_RSA (支持长度: HUKS_RSA_KEY_SIZE_512 HUKS_RSA_KEY_SIZE_768 HUKS_RSA_KEY_SIZE_1024 HUKS_RSA_KEY_SIZE_2048 HUKS_RSA_KEY_SIZE_3072 HUKS_RSA_KEY_SIZE_4096) | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | HUKS_PADDING_NONE HUKS_PADDING_PKCS1_V1_5 HUKS_PADDING_OAEP | HUKS_MODE_ECB | 【非必选】 | - -| HUKS_ALG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | HUKS_TAG_IV | HUKS_TAG_NONCE | HUKS_TAG_ASSOCIATED_DATA | HUKS_TAG_AE_TAG | -| ------------------------------------------------------------ | ------------------------ | ------------------------------------- | ---------------------------- | ----------- | -------------- | ------------------------ | --------------- | -| HUKS_ALG_AES (支持长度: HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256) | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE HUKS_PADDING_PKCS7 | HUKS_MODE_CBC | 【必选】 | 【非必选】 | 【非必选】 | 【非必选】 | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE | HUKS_MODE_CCM HUKS_MODE_GCM | 【非必选】 | 【必选】 | 【必选】 | 【非必选】 | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE | HUKS_MODE_CTR | 【必选】 | 【非必选】 | 【非必选】 | 【非必选】 | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_PKCS7 HUKS_PADDING_NONE | HUKS_MODE_ECB | 【必选】 | 【非必选】 | 【非必选】 | 【非必选】 | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE HUKS_PADDING_PKCS7 | HUKS_MODE_CBC | 【必选】 | 【非必选】 | 【非必选】 | 【必选】 | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE | HUKS_MODE_CCM HUKS_MODE_GCM | 【非必选】 | 【必选】 | 【必选】 | 【非必选】 | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE | HUKS_MODE_CTR | 【必选】 | 【非必选】 | 【非必选】 | 【非必选】 | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE HUKS_PADDING_PKCS7 | HUKS_MODE_ECB | 【必选】 | 【非必选】 | 【非必选】 | 【非必选】 | - -> **说明** -> -> 存储的 keyAlias 密钥别名最大为64字节 - -在使用示例前,需要先了解几个预先定义的变量: +### 签名验签 +```ts +/* + * 以下以SM2密钥的Callback操作使用为例 + */ +import huks from '@ohos.security.huks'; -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ----------- | ---- | ------------------------ | -| srcKeyAlias | string | 是 | 密钥别名。 | -| huksOptions | HuksOptions | 是 | 用于存放生成key所需TAG。 | -| encryptOptions | HuksOptions | 是 | 用于存放加密key所需TAG。 | -| decryptOptions | HuksOptions | 是 | 用于存放解密key所需TAG。 | +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let generateKeyAlias = 'sm2_Key'; +let importKeyAlias = 'importKeyAlias'; +let signVerifyInData = 'signVerifyInDataForTest'; +let handle; +let exportKey; +let finishOutData; -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 +/* 集成生成密钥参数集 */ +let generateKeyProperties = new Array(); +generateKeyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM2, +} +generateKeyProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY, +} +generateKeyProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, +} +generateKeyProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, +} +let genrateKeyOptions = { + properties: generateKeyProperties, + inData: new Uint8Array(new Array()) +} -**示例1:** +/* 集成签名参数集 */ +let signProperties = new Array(); +signProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM2, +} +signProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN +} +signProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, +} +signProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, +} +let signOptions = { + properties: signProperties, + inData: new Uint8Array(new Array()) +} -```ts -/* Cipher操作支持RSA、AES、SM4类型的密钥。 - * - * 以下以SM4 128密钥的Promise操作使用为例 - */ -import huks from '@ohos.security.huks'; +/* 集成验签参数集 */ +let verifyProperties = new Array(); +verifyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM2, +} +verifyProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +} +verifyProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, +} +verifyProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, +} +let verifyOptions = { + properties: verifyProperties, + inData: new Uint8Array(new Array()) +} function StringToUint8Array(str) { let arr = []; @@ -1133,33 +1066,47 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -function Uint8ArrayToString(fileData) { - let dataString = ''; - for (let i = 0; i < fileData.length; i++) { - dataString += String.fromCharCode(fileData[i]); - } - return dataString; +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); } async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await generateKeyItem(keyAlias, huksOptions) + await generateKeyItem(keyAlias, huksOptions, throwObject) .then((data) => { console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + huks.initSession(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1167,47 +1114,74 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise doInit`); + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; try { - await huks.initSession(keyAlias, huksOptions) + await initSession(keyAlias, huksOptions, throwObject) .then ((data) => { - console.info(`promise: doInit success, data = ${JSON.stringify(data)}`); + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); handle = data.handle; }) - .catch(error => { - console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`); + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); } } +function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.updateSession(handle, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; try { - await updateSession(handle, huksOptions) + await updateSession(handle, huksOptions, throwObject) .then ((data) => { console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - updateResult = Array.from(data.outData); }) .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.updateSession(handle, huksOptions, function (error, data) { + huks.finishSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1215,6 +1189,7 @@ function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - finishOutData = Uint8ArrayToString(new Uint8Array(updateResult)); + finishOutData = data.outData; console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.finishSession(handle, huksOptions, function (error, data) { + huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1247,30 +1227,37 @@ function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportKey = data.outData; }) .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { + huks.importKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1278,157 +1265,214 @@ function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -let IV = '0000000000000000'; -let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; -let srcKeyAlias = 'huksCipherSm4SrcKeyAlias'; -let encryptUpdateResult = new Array(); -let handle; -let updateResult = new Array(); -let finishOutData; - -async function testSm4Cipher() { - /* 集成生成密钥参数集 & 加密参数集 */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - - let propertiesEncrypt = new Array(); - propertiesEncrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - propertiesEncrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, - } - propertiesEncrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - propertiesEncrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - propertiesEncrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - propertiesEncrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), +async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter promise importKeyItem`); + let throwObject = {isThrow: false}; + try { + await importKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } - let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) +} + +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + +async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback deleteKeyItem`); + let throwObject = {isThrow: false}; + try { + await deleteKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } +} +async function testSm2SignVerify() { /* 生成密钥 */ - await publicGenKeyFunc(srcKeyAlias, huksOptions); + await publicGenKeyFunc(generateKeyAlias, genrateKeyOptions); - /* 进行密钥加密操作 */ - await publicInitFunc(srcKeyAlias, encryptOptions); - - encryptOptions.inData = StringToUint8Array(cipherInData); - await publicUpdateFunc(handle, encryptOptions); - encryptUpdateResult = updateResult; + /* 签名 */ + let signHandle; + let signFinishOutData; + await publicInitFunc(generateKeyAlias, signOptions); - encryptOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(handle, encryptOptions); - if (finishOutData === cipherInData) { - console.info('test finish encrypt err '); - } else { - console.info('test finish encrypt success'); - } + signHandle = handle; + signOptions.inData = StringToUint8Array(signVerifyInData) + await publicUpdateFunc(signHandle, signOptions); - /* 修改加密参数集为解密参数集 */ - propertiesEncrypt.splice(1, 1, { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - }); - let decryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) - } + signOptions.inData = new Uint8Array(new Array()); + await publicFinishFunc(signHandle, signOptions); + signFinishOutData = finishOutData; - /* 进行解密操作 */ - await publicInitFunc(srcKeyAlias, decryptOptions); + /* 导出密钥 */ + await publicExportKeyFunc(generateKeyAlias, genrateKeyOptions); - decryptOptions.inData = new Uint8Array(encryptUpdateResult); - await publicUpdateFunc(handle, decryptOptions); + /* 导入密钥 */ + verifyOptions.inData = exportKey; + await publicImportKeyFunc(importKeyAlias, verifyOptions); - decryptOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(handle, decryptOptions); - if (finishOutData === cipherInData) { - console.info('test finish decrypt success '); - } else { - console.info('test finish decrypt err'); - } + /* 验证签名 */ + let verifyHandle; + await publicInitFunc(importKeyAlias, verifyOptions); - await publicDeleteKeyFunc(srcKeyAlias, huksOptions); -} + verifyHandle = handle; -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testSm4Cipher') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testSm4Cipher(); - }) - } - .width('100%') - .height('100%') - } + verifyOptions.inData = StringToUint8Array(signVerifyInData) + await publicUpdateFunc(verifyHandle, verifyOptions); + + verifyOptions.inData = signFinishOutData; + await publicFinishFunc(verifyHandle, verifyOptions); + + await publicDeleteKeyFunc(generateKeyAlias, genrateKeyOptions); + await publicDeleteKeyFunc(importKeyAlias, genrateKeyOptions); } ``` -**示例2:** - +### 密钥协商 ```ts -/* Cipher操作支持RSA、AES、SM4类型的密钥。 - * - * 以下以AES128 GCM密钥的Promise操作使用为例 +/* + * 以下以X25519 256 TEMP密钥的Callback操作使用为例 */ import huks from '@ohos.security.huks'; +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let srcKeyAliasFirst = "AgreeX25519KeyFirstAlias"; +let srcKeyAliasSecond = "AgreeX25519KeySecondAlias"; +let agreeX25519InData = 'AgreeX25519TestIndata'; +let finishOutData; +let handle; +let exportKey; +let exportKeyFrist; +let exportKeySecond; + +/* 集成生成密钥参数集 */ +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_X25519, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +let HuksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} + +/* 集成第一个协商参数集 */ +let finishProperties = new Array(); +finishProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_TEMP, +} +finishProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, + value: true +} +finishProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +finishProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, +} +finishProperties[4] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +finishProperties[5] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, +} +finishProperties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, + value: StringToUint8Array(srcKeyAliasFirst+ 'final'), +} +finishProperties[7] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +finishProperties[8] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, +} +let finishOptionsFrist = { + properties: finishProperties, + inData: StringToUint8Array(agreeX25519InData) +} +/* 集成第二个协商参数集 */ +let finishOptionsSecond = { + properties: finishProperties, + inData: StringToUint8Array(agreeX25519InData) +} +finishOptionsSecond.properties.splice(6, 1, { + tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, + value: StringToUint8Array(srcKeyAliasSecond + 'final'), +}) + function StringToUint8Array(str) { let arr = []; for (let i = 0, j = str.length; i < j; ++i) { @@ -1437,33 +1481,47 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -function Uint8ArrayToString(fileData) { - let dataString = ''; - for (let i = 0; i < fileData.length; i++) { - dataString += String.fromCharCode(fileData[i]); - } - return dataString; +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); } async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await generateKeyItem(keyAlias, huksOptions) + await generateKeyItem(keyAlias, huksOptions, throwObject) .then((data) => { console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + huks.initSession(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1471,47 +1529,74 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise doInit`); + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; try { - await huks.initSession(keyAlias, huksOptions) + await initSession(keyAlias, huksOptions, throwObject) .then ((data) => { - console.info(`promise: doInit success, data = ${JSON.stringify(data)}`); + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); handle = data.handle; }) - .catch(error => { - console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`); + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); } } +function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.updateSession(handle, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; try { - await updateSession(handle, huksOptions) + await updateSession(handle, huksOptions, throwObject) .then ((data) => { console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - updateResult = Array.from(data.outData); }) .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.updateSession(handle, huksOptions, function (error, data) { + huks.finishSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1519,6 +1604,7 @@ function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - updateResult = updateResult.concat(Array.from(data.outData)); + finishOutData = data.outData; console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.finishSession(handle, huksOptions, function (error, data) { + huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1551,27 +1642,34 @@ function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportKey = data.outData; }) .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { @@ -1582,227 +1680,165 @@ function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -let AAD = '0000000000000000'; -let NONCE = '000000000000'; -let AEAD = '0000000000000000'; -let cipherInData = 'Hks_AES_Cipher_Test_00000000000000000000000000000000000000000000000000000_string'; -let srcKeyAlias = 'huksCipherSm4SrcKeyAlias'; -let updateResult = new Array(); -let encryptUpdateResult = new Array(); -let decryptUpdateResult = new Array(); -let handle; -let finishOutData; - -async function testAesCipher() { - /* 集成生成密钥参数集 & 加密参数集 */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_GCM, - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) +async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback deleteKeyItem`); + let throwObject = {isThrow: false}; + try { + await deleteKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } +} - let propertiesEncrypt = new Array(); - propertiesEncrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - propertiesEncrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, - } - propertiesEncrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, - } - propertiesEncrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - propertiesEncrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_GCM, - } - propertiesEncrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, - } - propertiesEncrypt[6] = { - tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA, - value: StringToUint8Array(AAD), - } - propertiesEncrypt[7] = { - tag: huks.HuksTag.HUKS_TAG_NONCE, - value: StringToUint8Array(NONCE), - } - propertiesEncrypt[8] = { - tag: huks.HuksTag.HUKS_TAG_AE_TAG, - value: StringToUint8Array(AEAD), - } - let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) - } - - /* 生成密钥 */ - await publicGenKeyFunc(srcKeyAlias, huksOptions); - - /* 进行密钥加密操作 */ - await publicInitFunc(srcKeyAlias, encryptOptions); - - encryptOptions.inData = StringToUint8Array(cipherInData.slice(0,64)); - await publicUpdateFunc(handle, encryptOptions); - encryptUpdateResult = updateResult; - - encryptOptions.inData = StringToUint8Array(cipherInData.slice(64,80)); - await publicFinishFunc(handle, encryptOptions); - encryptUpdateResult = updateResult; - finishOutData = Uint8ArrayToString(new Uint8Array(encryptUpdateResult)); - if (finishOutData === cipherInData) { - console.info('test finish encrypt err '); - } else { - console.info('test finish encrypt success'); - } - - /* 修改加密参数集为解密参数集 */ - propertiesEncrypt.splice(1, 1, { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - }); - propertiesEncrypt.splice(8, 1, { - tag: huks.HuksTag.HUKS_TAG_AE_TAG, - value: new Uint8Array(encryptUpdateResult.splice(encryptUpdateResult.length - 16,encryptUpdateResult.length)) - }); - let decryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) - } - - /* 进行解密操作 */ - await publicInitFunc(srcKeyAlias, decryptOptions); +async function testAgree() { + /* 1.生成两个密钥并导出 */ + await publicGenKeyFunc(srcKeyAliasFirst, HuksOptions); + await publicGenKeyFunc(srcKeyAliasSecond, HuksOptions); - decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(0,64)); - await publicUpdateFunc(handle, decryptOptions); - decryptUpdateResult = updateResult; + await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions); + exportKeyFrist = exportKey; + await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions); + exportKeySecond = exportKey; - decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(64,encryptUpdateResult.length)); - await publicFinishFunc(handle, decryptOptions); - decryptUpdateResult = updateResult; - finishOutData = Uint8ArrayToString(new Uint8Array(decryptUpdateResult)); - if (finishOutData === cipherInData) { - console.info('test finish decrypt success '); - } else { - console.info('test finish decrypt err'); - } + /* 对第一个密钥进行协商 */ + await publicInitFunc(srcKeyAliasFirst, HuksOptions); + HuksOptions.inData = exportKeySecond; + await publicUpdateFunc(handle, HuksOptions); + await publicFinishFunc(handle, finishOptionsFrist); - await publicDeleteKeyFunc(srcKeyAlias, huksOptions); -} + /* 对第二个密钥进行协商 */ + await publicInitFunc(srcKeyAliasSecond, HuksOptions); + HuksOptions.inData = exportKeyFrist; + await publicUpdateFunc(handle, HuksOptions); + await publicFinishFunc(handle, finishOptionsSecond); -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testAesCipher') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testAesCipher(); - }) - } - .width('100%') - .height('100%') - } + await publicDeleteKeyFunc(srcKeyAliasFirst, HuksOptions); + await publicDeleteKeyFunc(srcKeyAliasSecond, HuksOptions); } ``` -### 密钥签名验签 - -签名:给我们将要发送的数据,做上一个唯一签名;验签: 对发送者发送过来的签名进行验证 。 - -开发步骤如下: - -1. 生成密钥。 -2. 密钥签名。 -3. 导出签名密钥。 -4. 导入签名密钥。 -5. 密钥验签。 - -**支持的密钥类型:** - -仅HksInit对paramSet中参数有要求,其他三段式接口对paramSet无要求 - -| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | HUKS_ALG_PADDING | HUKS_TAG_DIGEST | -| ------------------ | ------------------------------------------------------------ | ---------------------------------------------- | ----------------------- | ------------------------------------------------------------ | -| HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512 HUKS_RSA_KEY_SIZE_768 HUKS_RSA_KEY_SIZE_1024 HUKS_RSA_KEY_SIZE_2048 HUKS_RSA_KEY_SIZE_3072 HUKS_RSA_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PKCS1_V1_5 | HUKS_DIGEST_MD5 HUKS_DIGEST_NONE HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | -| HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512 HUKS_RSA_KEY_SIZE_768 HUKS_RSA_KEY_SIZE_1024 HUKS_RSA_KEY_SIZE_2048 HUKS_RSA_KEY_SIZE_3072 HUKS_RSA_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PSS | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | -| HUKS_ALG_DSA | HUKS_RSA_KEY_SIZE_1024 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | 【非必选】 | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | -| HUKS_ALG_ECC | HUKS_ECC_KEY_SIZE_224 HUKS_ECC_KEY_SIZE_256 HUKS_ECC_KEY_SIZE_384 HUKS_ECC_KEY_SIZE_521 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | 【非必选】 | HUKS_DIGEST_NONE HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | - -Ed25519的签名验签是在算法引擎中做的HASH操作,因此该算法的三段式接口处理较特殊: - -Update过程只将inData发送到Core中记录在ctx中,不进行Hash计算,最后在finish操作时,对inData组合后的数据进行签名、验签计算. - -| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | -| ------------------ | ---------------------------- | ----------------------------------------------- | -| HUKS_ALG_ED25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | - -> **说明** -> -> 存储的 keyAlias 密钥别名最大为64字节 - -在使用示例前,需要先了解几个预先定义的变量: +### 密钥派生 +```ts +/* + * 以下以HKDF256密钥的Promise操作使用为例 + */ +import huks from '@ohos.security.huks'; -| 参数名 | 类型 | 必填 | 说明 | -| ----------------- | ----------- | ---- | ------------------------ | -| generateKeyAlias | string | 是 | 生成密钥别名。 | -| importKeyAlias | string | 是 | 导入密钥别名。 | -| genrateKeyOptions | HuksOptions | 是 | 用于存放生成key所需TAG。 | -| signOptions | HuksOptions | 是 | 用于存放签名key所需TAG。 | -| verifyOptions | HuksOptions | 是 | 用于存放验签key所需TAG。 | +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let srcKeyAlias = "hkdf_Key"; +let deriveHkdfInData = "deriveHkdfTestIndata"; +let handle; +let finishOutData; +let HuksKeyDeriveKeySize = 32; -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 +/* 集成生成密钥参数集 */ +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DERIVE, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} -**示例:** +/* 集成init时密钥参数集 */ +let initProperties = new Array(); +initProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_HKDF, +} +initProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DERIVE, +} +initProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256, +} +initProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_DERIVE_KEY_SIZE, + value: HuksKeyDeriveKeySize, +} +let initOptions = { + properties: initProperties, + inData: new Uint8Array(new Array()) +} -```ts -/* Sign/Verify操作支持RSA、ECC、SM2、ED25519、DSA类型的密钥。 - * - * 以下以SM2密钥的Callback操作使用为例 - */ -import huks from '@ohos.security.huks'; +/* 集成finish时密钥参数集 */ +let finishProperties = new Array(); +finishProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT, +} +finishProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, + value: true, +} +finishProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +finishProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, +} +finishProperties[4] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +finishProperties[5] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, +} +finishProperties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, + value: StringToUint8Array(srcKeyAlias), +} +finishProperties[7] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +finishProperties[8] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, +} +let finishOptions = { + properties: finishProperties, + inData: new Uint8Array(new Array()) +} function StringToUint8Array(str) { let arr = []; @@ -1812,22 +1848,7 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { @@ -1838,28 +1859,33 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); +async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await initSession(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) - .catch((error) => { - console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`); + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { huks.initSession(keyAlias, huksOptions, function (error, data) { @@ -1870,27 +1896,34 @@ function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; }) - .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { huks.updateSession(handle, huksOptions, function (error, data) { @@ -1901,28 +1934,33 @@ function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - finishOutData = data.outData;; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { huks.finishSession(handle, huksOptions, function (error, data) { @@ -1933,62 +1971,37 @@ function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); - exportKey = data.outData; + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); + if (throwObject.isThrow) { + throw(error); } else { - resolve(data); + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); } }); - } catch (error) { - throw(error); - } - }); -} - -async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise importKeyItem`); - try { - await importKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); } catch (error) { - console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { - huks.importKeyItem(keyAlias, huksOptions, function (error, data) { + huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1996,6 +2009,7 @@ function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); @@ -2003,1471 +2017,563 @@ function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter callback deleteKeyItem`); + let throwObject = {isThrow: false}; try { - await deleteKeyItem(keyAlias, huksOptions) + await deleteKeyItem(keyAlias, huksOptions, throwObject) .then ((data) => { console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} +async function testDerive() { + /* 生成密钥 */ + await publicGenKeyFunc(srcKeyAlias, huksOptions); -let signVerifyInData = 'signVerifyInDataForTest'; -let generateKeyAlias = 'generateKeyAliasForTest'; -let importKeyAlias = 'importKeyAliasForTest'; -let handle; -let exportKey; -let finishOutData; + /* 进行派生操作 */ + await publicInitFunc(srcKeyAlias, initOptions); -/* 集成生成密钥参数集 */ -let generateKeyProperties = new Array(); -generateKeyProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM2, -} -generateKeyProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY, -} -generateKeyProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, -} -generateKeyProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, -} -let genrateKeyOptions = { - properties: generateKeyProperties, - inData: new Uint8Array(new Array()) -} - -/* 集成签名参数集 */ -let signProperties = new Array(); -signProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM2, -} -signProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN -} -signProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, -} -signProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, -} -let signOptions = { - properties: signProperties, - inData: new Uint8Array(new Array()) -} - -/* 集成验签参数集 */ -let verifyProperties = new Array(); -verifyProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM2, -} -verifyProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY -} -verifyProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, -} -verifyProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, -} -let verifyOptions = { - properties: verifyProperties, - inData: new Uint8Array(new Array()) -} - -async function testSm2SignVerify() { - /* 生成密钥 */ - await publicGenKeyFunc(generateKeyAlias, genrateKeyOptions); - - /* 签名 */ - let signHandle; - let signFinishOutData; - await publicInitFunc(generateKeyAlias, signOptions); - - signHandle = handle; - signOptions.inData = StringToUint8Array(signVerifyInData) - await publicUpdateFunc(signHandle, signOptions); - - signOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(signHandle, signOptions); - signFinishOutData = finishOutData; - - /* 导出密钥 */ - await publicExportKeyFunc(generateKeyAlias, genrateKeyOptions); - - /* 导入密钥 */ - verifyOptions.inData = exportKey; - await publicImportKeyFunc(importKeyAlias, verifyOptions); - - /* 验证签名 */ - let verifyHandle; - await publicInitFunc(importKeyAlias, verifyOptions); - - verifyHandle = handle; - - verifyOptions.inData = StringToUint8Array(signVerifyInData) - await publicUpdateFunc(verifyHandle, verifyOptions); - - verifyOptions.inData = signFinishOutData; - await publicFinishFunc(verifyHandle, verifyOptions); - - await publicDeleteKeyFunc(generateKeyAlias, genrateKeyOptions); - await publicDeleteKeyFunc(importKeyAlias, genrateKeyOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testSm2SignVerify') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testSm2SignVerify(); - }) - } - .width('100%') - .height('100%') - } -} -``` - -### 密钥协商 - -两个或多个对象生成会话密钥,通过会话密钥进行交流 。 - -开发步骤如下: - -1. 生成两个密钥。 -2. 分别导出密钥。 -3. 交叉进行密钥协商。 - -**支持的密钥类型:** - -仅HksInit和HksFinish接口对paramSet参数有要求,HksUpdate接口对paramSet无要求 - -HksInit对paramSet中参数的要求 - -| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | -| ------------------ | ------------------------------------------------------------ | ---------------------- | -| HUKS_ALG_ECDH | HUKS_ECC_KEY_SIZE_224 HUKS_ECC_KEY_SIZE_256 HUKS_ECC_KEY_SIZE_384 HUKS_ECC_KEY_SIZE_521 | HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_DH | HUKS_DH_KEY_SIZE_2048 HUKS_DH_KEY_SIZE_3072 HUKS_DH_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_X25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_AGREE | - -HksFinish对paramSet中参数的要求: - -派生后的密钥作为对称密钥进行使用 - -| HUKS_TAG_KEY_STORAGE_FLAG | HUKS_TAG_KEY_ALIAS | HUKS_TAG_IS_KEY_ALIAS | HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE | HUKS_TAG_PURPOSE | HUKS_TAG_PADDING | HUKS_TAG_DIGEST | HUKS_TAG_BLOCK_MODE | -| ------------------------------ | ------------------ | --------------------- | ------------------ | ------------------------------------------------------------ | -------------------------------------------------- | ------------------ | ------------------------------------------------------------ | ------------------------------------------- | -| 未设置 或者 HUKS_STORAGE_TEMP | 不需要 | TRUE | 不需要 | 不需要 | 不需要 | 不需要 | 不需要 | 不需要 | -| HUKS_STORAGE_PERSISTENT | 【必选】最大64字节 | TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_PKCS7 | 【非必选】 | HUKS_MODE_CCM HUKS_MODE_GCM HUKS_MODE_CTP | -| HUKS_STORAGE_PERSISTENT | 【必选】最大64字节 | TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_DERIVE | 【非必选】 | HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | 【非必选】 | -| HUKS_STORAGE_PERSISTENT | 【必选】最大64字节 | TRUE | HUKS_ALG_HMAC | 8的倍数(单位:bit) | HUKS_KEY_PURPOSE_MAC | 【非必选】 | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | 【非必选】 | - -> **说明** -> -> HUKS_ALG_AES的SIZE需要满足:协商后的密钥长度(转换成bit)>=选择的HUKS_TAG_KEY_SIZE -> -> 存储的 keyAlias 密钥别名最大为64字节 - -在使用示例前,需要先了解几个预先定义的变量: - -| 参数名 | 类型 | 必填 | 说明 | -| ------------------- | ----------- | ---- | -------------------------------------- | -| srcKeyAliasFirst | string | 是 | 生成密钥别名。 | -| srcKeyAliasSecond | string | 是 | 生成密钥别名,用于结果对比。 | -| huksOptions | HuksOptions | 是 | 用于存放生成key所需TAG。 | -| finishOptionsFrist | HuksOptions | 是 | 用于存放协商key所需TAG。 | -| finishOptionsSecond | HuksOptions | 是 | 用于存放协商key所需TAG,用于结果对比。 | - -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 - -**示例:** - -```ts -/* agree操作支持ECDH、DH、X25519类型的密钥。 - * - * 以下以X25519 256 TEMP密钥的Promise操作使用为例 - */ -import huks from '@ohos.security.huks'; - -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} - -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - try { - await initSession(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch((error) => { - console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - try { - await updateSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - try { - await finishSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback export`); - try { - await exportKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); - exportKey = data.outData; - }) - .catch(error => { - console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - try { - await deleteKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -let srcKeyAliasFirst = "AgreeX25519KeyFirstAlias"; -let srcKeyAliasSecond = "AgreeX25519KeySecondAlias"; -let agreeX25519InData = 'AgreeX25519TestIndata'; -let handle; -let exportKey; -let exportKeyFrist; -let exportKeySecond; - -async function testAgree() { - /* 集成生成密钥参数集 */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_X25519, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - let HuksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - - /* 1.生成两个密钥并导出 */ - await publicGenKeyFunc(srcKeyAliasFirst, HuksOptions); - await publicGenKeyFunc(srcKeyAliasSecond, HuksOptions); - - await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions); - exportKeyFrist = exportKey; - await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions); - exportKeySecond = exportKey; - - /* 集成第一个协商参数集 */ - let finishProperties = new Array(); - finishProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_TEMP, - } - finishProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, - value: true - } - finishProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - finishProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, - } - finishProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - finishProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, - } - finishProperties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, - value: StringToUint8Array(srcKeyAliasFirst+ 'final'), - } - finishProperties[7] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - finishProperties[8] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB, - } - let finishOptionsFrist = { - properties: finishProperties, - inData: StringToUint8Array(agreeX25519InData) - } - - /* 对第一个密钥进行协商 */ - await publicInitFunc(srcKeyAliasFirst, HuksOptions); - HuksOptions.inData = exportKeySecond; - await publicUpdateFunc(handle, HuksOptions); - await publicFinishFunc(handle, finishOptionsFrist); - - /* 集成第二个协商参数集 */ - let finishOptionsSecond = { - properties: finishProperties, - inData: StringToUint8Array(agreeX25519InData) - } - finishOptionsSecond.properties.splice(6, 1, { - tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, - value: StringToUint8Array(srcKeyAliasSecond + 'final'), - }) - - /* 对第二个密钥进行协商 */ - await publicInitFunc(srcKeyAliasSecond, HuksOptions); - HuksOptions.inData = exportKeyFrist; - await publicUpdateFunc(handle, HuksOptions); - await publicFinishFunc(handle, finishOptionsSecond); - - - await publicDeleteKeyFunc(srcKeyAliasFirst, HuksOptions); - await publicDeleteKeyFunc(srcKeyAliasSecond, HuksOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testAgree') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testAgree(); - }) - } - .width('100%') - .height('100%') - } -} -``` - -### 密钥派生 - -从一个密钥产生出一个或者多个密钥。 - -开发步骤如下: - -1. 生成密钥。 -2. 进行密钥派生。 - -**支持的密钥类型:** - -仅HksInit和HksFinish接口对paramSet参数有要求,HksUpdate接口对paramSet无要求 - -HksInit对paramSet中参数的要求 - -| HUKS_TAG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_DERIVE_KEY_SIZE | -| ------------------------------------------------------------ | ----------------------- | ---------------------------------------------------------- | ------------------------ | -| HUKS_ALG_HKDF (支持长度: HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256) | HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | 【必选】 | -| HUKS_ALG_PBKDF2 (支持长度: HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256) | HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | 【必选】 | - -HksFinish对paramSet中参数的要求: - -派生后的密钥作为对称密钥进行使用 - -| HUKS_TAG_KEY_STORAGE_FLAG | HUKS_TAG_KEY_ALIAS | HUKS_TAG_IS_KEY_ALIAS | HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE | HUKS_TAG_PURPOSE | HUKS_TAG_PADDING | HUKS_TAG_DIGEST | HUKS_TAG_BLOCK_MODE | -| ------------------------------ | ------------------ | --------------------- | ------------------ | ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------ | ------------------------------------------- | -| 未设置 或者 HUKS_STORAGE_TEMP | 不需要 | TRUE | 不需要 | 不需要 | 不需要 | 不需要 | 不需要 | 不需要 | -| HUKS_STORAGE_PERSISTENT | 【必选】最大64字节 | TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE HUKS_PADDING_PKCS7 | 【非必选】 | HUKS_MODE_CBC HUKS_MODE_ECB | -| HUKS_STORAGE_PERSISTENT | 【必选】最大64字节 | TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE | 【非必选】 | HUKS_MODE_CCM HUKS_MODE_GCM HUKS_MODE_CTR | -| HUKS_STORAGE_PERSISTENT | 【必选】最大64字节 | TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_DERIVE | 【非必选】 | HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | 【非必选】 | -| HUKS_STORAGE_PERSISTENT | 【必选】最大64字节 | TRUE | HUKS_ALG_HMAC | 8的倍数(单位:bit) | HUKS_KEY_PURPOSE_MAC | 【非必选】 | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | 【非必选】 | - -> **说明** -> -> HUKS_ALG_AES的SIZE需要满足:派生后的密钥长度(转换成bit)>=选择的HUKS_TAG_KEY_SIZE -> -> 存储的 keyAlias 密钥别名最大为64字节 - -在使用示例前,需要先了解几个预先定义的变量: - -| 参数名 | 类型 | 必填 | 说明 | -| ------------- | ----------- | ---- | ---------------- | -| srcKeyAlias | string | 是 | 生成密钥别名。 | -| huksOptions | HuksOptions | 是 | 生成密钥参数集。 | -| finishOptions | HuksOptions | 是 | 派生密钥参数集。 | - -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 - -**示例:** - -```ts -/* derive操作支持HKDF、pbdkf类型的密钥。 - * - * 以下以HKDF256密钥的Promise操作使用为例 - */ -import huks from '@ohos.security.huks'; - -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} - -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise doInit`); - try { - await huks.initSession(keyAlias, huksOptions) - .then ((data) => { - console.info(`promise: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch(error => { - console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - try { - await updateSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - try { - await finishSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - try { - await deleteKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); + initOptions.inData = StringToUint8Array(deriveHkdfInData); + await publicUpdateFunc(handle, initOptions); + await publicFinishFunc(handle, finishOptions); + + await publicDeleteKeyFunc(srcKeyAlias, huksOptions); } +``` -let deriveHkdfInData = "deriveHkdfTestIndata"; -let srcKeyAlias = "deriveHkdfKeyAlias"; -let handle; -let HuksKeyDeriveKeySize = 32; +## 密钥访问控制 -async function testDerive() { - /* 集成生成密钥参数集 */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DERIVE, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } +HUKS提供了全面完善的密钥访问控制能力,确保存储在HUKS中的密钥被合法正确的访问。 - /* 生成密钥 */ - await publicGenKeyFunc(srcKeyAlias, huksOptions); +首先,业务只能访问属于自己的密钥,即只能访问通过HUKS生成或导入的密钥。 +其次,支持密钥的用户身份认证访问控制,对于高安敏感的业务密钥,需要在使用密钥的时候,再次要求用户即时的验证锁屏密码或生物特征,验证通过后,才能使用业务密钥。 +除此之外,HUKS还支持严格限制密钥的使用用途,如支持只允许AES密钥进行加密解密,只允许RSA密钥进行签名验签。 - /* 调整init时的参数集 */ - huksOptions.properties.splice(0, 1, { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_HKDF, - }); - huksOptions.properties.splice(3, 1, { - tag: huks.HuksTag.HUKS_TAG_DERIVE_KEY_SIZE, - value: HuksKeyDeriveKeySize, - }); +**用户身份认证访问控制** - let finishProperties = new Array(); - finishProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT, - } - finishProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, - value: true, - } - finishProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - finishProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, - } - finishProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - finishProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, - } - finishProperties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, - value: StringToUint8Array(srcKeyAlias), - } - finishProperties[7] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - finishProperties[8] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB, - } - let finishOptions = { - properties: finishProperties, - inData: new Uint8Array(new Array()) - } +生成或导入密钥时,可以指定密钥必须经过用户身份认证后才能使用。您可以指定用于解锁设备锁屏的凭据(锁屏密码、指纹、人脸)的子集进行身份认证。在生成/导入密钥后,即使应用进程被攻击也不会导致未经用户授权的密钥访问,一般用于高敏感且高级别安全保护的场景,比如免密登录、免密支付、自动填充密码保护场景。 - /* 进行派生操作 */ - await publicInitFunc(srcKeyAlias, huksOptions); +除用户身份认证外,应用还须将密钥的授权访问类型(即失效条件)设置为以下两种类型之一: +- **清除锁屏密码后密钥永久无效。** 设置此模式的前提是当前用户已经设置了锁屏密码,在生成/导入密钥后,一旦清除了锁屏密码,此类密钥将永久失效。注意,修改密码不会导致失效情况发生。此模式适合那些需要锁屏密码授权访问或用户强相关的数据保护的场景。 +- **用户新录入生物特征后永久无效。** 此模式需要当前用户至少录入了一个生物特征(如指纹)才能生效,在生成/导入密钥后,一旦录入新的生物特征,这些密钥将永久失效。注意,仅删除生物特征不会导致失效情况发生。如果您不希望新录入的生物特征后,用户还可以授权访问原有数据(密钥保护的数据),那么可以使用此模式,如免密登录,免密支付等场景。 - huksOptions.inData = StringToUint8Array(deriveHkdfInData); - await publicUpdateFunc(handle, huksOptions); - await publicFinishFunc(handle, finishOptions); +此外,为了保证密钥使用时用户认证结果的有效性(不可重放),HUKS支持挑战值校验:在身份认证前,需要从HUKS获取挑战值(调用[huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9)返回的[HuksSessionHandle](../reference/apis/js-apis-huks.md#hukssessionhandle9)中)传给用户身份认证方法([userIAM_userAuth.getAuthInstance](../reference/apis/js-apis-useriam-userauth.md#authinstance9)),然后在密钥操作时校验认证令牌的挑战值。 - huksOptions.properties.splice(0, 1, { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - }); - huksOptions.properties.splice(3, 1, { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, - }); +**开发流程** - await publicDeleteKeyFunc(srcKeyAlias, huksOptions); -} +设置了二次用户身份认证的密钥,需要先初始化密钥会话并获取挑战值,然后将HUKS生成的挑战值传至用户身份认证方法进行用户身份认证,认证通过后获取一个认证令牌,将认证令牌传至HUKS进行密钥操作。 -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testDerive') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testDerive(); - }) - } - .width('100%') - .height('100%') - } -} -``` +![huks_key_user_auth_work_flow](./figures/huks_key_user_auth_work_flow.png) -### 密钥mac +**接口说明** -基于密钥数据进行mac摘要所获得的一个哈希值。 +1. 生成或导入密钥时,在密钥属性集中需指定三个参数:用户认证类型[HuksUserAuthType](../reference/apis/js-apis-huks.md#huksuserauthtype9)、授权访问类型[HuksAuthAccessType](../reference/apis/js-apis-huks.md#huksauthaccesstype9)、挑战值类型[HuksChallengeType](../reference/apis/js-apis-huks.md#hukschallengetype9)。 -开发步骤如下: + **表3** 用户认证类型:三种类型的子集 + | 名称 | 值 | 说明 | + | ------------------------------- |---|------------------------ | + | HUKS_USER_AUTH_TYPE_FINGERPRINT |0x0001 | 用户认证类型为指纹,允许和人脸、锁屏密码同时设置 | + | HUKS_USER_AUTH_TYPE_FACE |0x0002 | 用户认证类型为人脸 ,允许和指纹、锁屏密码同时设置 | + | HUKS_USER_AUTH_TYPE_PIN |0x0004 | 用户认证类型为锁屏密码,允许和人脸、指纹同时设置 | -1. 生成密钥。 -2. 密钥mac。 + **表4** 安全访问类型:二选一 + | 名称 | 值 | 说明 | + | --------------------------------------- | ---- | ------------------------------------------------ | + | HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | 清除锁屏密码后密钥无法访问。 | + | HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | 新录入生物特征后密钥无法访问,用户认证类型须包含生物认证类型。 | -**支持的密钥类型:** + **表5** 挑战值类型:三选一 + | 名称 | 值 | 说明 | + | ------------------------------- | ---- | ------------------------------ | + | HUKS_CHALLENGE_TYPE_NORMAL | 0 | 普通类型,每次密钥的使用需要独立的一次用户认证 | + | HUKS_CHALLENGE_TYPE_CUSTOM | 1 | 自定义类型,支持和多个密钥共享一次用户认证| + | HUKS_CHALLENGE_TYPE_NONE | 2 | 无挑战值类型,用户认证时不需要挑战值 | -HksInit对paramSet中参数的要求,其他三段式接口对paramSet无要求 + > **注意** + > + > 当指定挑战值类型为**HUKS_CHALLENGE_TYPE_NONE** 时,不需要传递挑战值,但是存在新的限制:在用户身份认证后,一段时间内允许访问该密钥,超时后不能访问,需要重新认证才能访问。因此应用需要额外指定超时时间**HUKS_TAG_AUTH_TIMEOUT**属性(最大60秒)。 -| HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | -| ------------ | ---------- | ------------------- | ------------------------------------------------------------ | ---------- | ---------- | -| HUKS_ALG_HMAC | 【非必选】 | HUKS_KEY_PURPOSE_MAC | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | 【非必选】 | 【非必选】 | -| HUKS_ALG_SM3 | 【非必选】 | HUKS_KEY_PURPOSE_MAC | HUKS_DIGEST_SM3 | 【非必选】 | 【非必选】 | -> **说明** -> -> 存储的 keyAlias 密钥别名最大为64字节 +2. 使用密钥时,先初始化密钥会话,然后根据密钥生成/导入阶段指定的挑战值类型属性是否需要获取挑战值,或组装新的挑战值。 + + **表6** 使用密钥的接口介绍 -在使用示例前,需要先了解几个预先定义的变量: + | 接口名 | 描述 | + | -------------------------------------- | ----------------------------| + |initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| 初始化密钥会话,获取挑战值| + |updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| 分段操作数据,传递认证令牌| + |finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| 结束密钥会话,传递认证令牌| -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ----------- | ---- | -------------- | -| srcKeyAlias | string | 是 | 生成密钥别名。 | -| huksOptions | HuksOptions | 是 | 密钥参数集。 | -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 -**示例:** +**开发步骤** +1. 生成密钥并指定指纹访问控制和相关属性 ```ts -/* mac操作支持HMAC、SM3类型的密钥。 - * - * 以下以SM3 256密钥的Promise操作使用为例 - */ import huks from '@ohos.security.huks'; -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let keyAlias = 'dh_key_fingerprint_access'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, } - -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, } - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, } - -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - try { - await initSession(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch((error) => { - console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, } - -function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, } - -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - try { - await updateSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } +// 指定密钥身份认证的类型:指纹 +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, + value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT } - -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); +// 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效 +properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, + value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL } - -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - try { - await finishSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } +// 指定挑战值的类型:默认类型 +properties[7] = { + tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, + value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL } - -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); +/* + * 生成密钥 + */ +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { try { - await deleteKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -let srcKeyAlias = "sm3KeyAlias"; -let hmacInData = 'sm3TestIndata'; -let handle; - -async function testMac() { - /* 集成生成密钥参数集 */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM3, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_MAC, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, - } - let huksOptions = { - properties:properties, - inData:new Uint8Array(new Array()) - } - - /* 生成密钥 */ - await publicGenKeyFunc(srcKeyAlias, huksOptions); - - /* 修改init时的参数集并进行mac操作 */ - huksOptions.properties.splice(3, 3); - await publicInitFunc(srcKeyAlias, huksOptions); - huksOptions.inData = StringToUint8Array(hmacInData); - await publicUpdateFunc(handle, huksOptions); - huksOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(handle, huksOptions); - - huksOptions.properties.splice(1, 0, { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, - }); - await publicDeleteKeyFunc(srcKeyAlias, huksOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testMac') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testMac(); - }) + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); } - .width('100%') - .height('100%') + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); } + }); } -``` - -### AttestID - -应用生成非对称密钥后,可以通过id attestation获取证书链,ID Attestation包含支持如下设备信息: BRAND, DEVICE, PRODUCT, SERIAL, IMEI, MEID, MANUFACTURER, MODEL, SOCID, UDID。 - -应用还可以通过key attestation获取证书链。 - -ID Attestation和Key Attestation只有拥有TEE环境的设备才具备该功能。 - -开发步骤如下: - -1. 生成证书。 -2. 获取证书信息。 -**支持的密钥类型:** - -RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, X25519 - -> **说明** -> -> 存储的 keyAlias 密钥别名最大为64字节 - -在使用示例前,需要先了解几个预先定义的变量: - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------- | ---- | ------------------------------------ | -| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 | -| options | HuksOptions | 是 | 用于获取证书时指定所需参数与数据。 | +async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; + try { + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 +async function TestGenKeyForFingerprintAccessControl() { + await publicGenKeyFunc(keyAlias, huksOptions); +} +``` -**示例:** +2. 初始化密钥会话获取挑战值并发起指纹认证获取认证令牌 ```ts -/* 证书AttestID操作示例如下*/ import huks from '@ohos.security.huks'; +import userIAM_userAuth from '@ohos.userIAM.userAuth'; -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let srcKeyAlias = 'sm4_key_fingerprint_access'; +let handle; +let challenge; +let fingerAuthToken; +let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +/* 集成生成密钥参数集 & 加密参数集 */ +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + throwObject.isThrow = true; + throw(error); } + }); } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); +async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + challenge = data.challenge; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function userIAMAuthFinger(huksChallenge:Uint8Array) { + // 获取认证对象 + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // 订阅认证结果 + try { + auth.on("result", { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + /* 认证成功获取认证令牌 */ + fingerAuthToken = result.token; + } }); + console.log("subscribe authentication event success"); + } catch (error) { + console.log("subscribe authentication event failed " + error); + } + + // 开始认证 + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } +} + +async function testInitAndAuthFinger() { + /* 初始化密钥会话获取挑战值 */ + await publicInitFunc(srcKeyAlias, huksOptions); + /* 调用userIAM进行身份认证 */ + userIAMAuthFinger(challenge); } +``` -async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback attestKeyItem`); - try { - await attestKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } +3. 传入认证令牌进行数据操作 +```ts +/* + * 以下以SM4 128密钥的Callback操作使用为例 + */ +import huks from '@ohos.security.huks'; + +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let srcKeyAlias = 'sm4_key_fingerprint_access'; +let IV = '1234567890123456'; +let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; +let handle; +let fingerAuthToken; +let updateResult = new Array(); +let finishOutData; + +/* 集成生成密钥参数集 & 加密参数集 */ +let propertiesEncrypt = new Array(); +propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, +} +propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), +} +let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) } -function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise{ - return new Promise((resolve, reject) => { - try { - huks.attestKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); +function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); +function updateSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { try { - await deleteKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); + huks.updateSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } + throwObject.isThrow = true; + throw(error); + } + }); +} + +async function publicUpdateFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; + try { + await updateSession(handle, huksOptions, token, throwObject) + .then ((data) => { + console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); +function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); } - }); + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + +async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, token, throwObject) + .then ((data) => { + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -let securityLevel = StringToUint8Array('sec_level'); -let challenge = StringToUint8Array('challenge_data'); -let versionInfo = StringToUint8Array('version_info'); -let udid = StringToUint8Array('udid'); -let serial = StringToUint8Array('serial'); -let deviceId = StringToUint8Array('device_id'); -let idAliasString = "id attest"; - -async function testAttestId() { - let aliasString = idAliasString; - let aliasUint8 = StringToUint8Array(aliasString); - - /* 集成生成密钥参数集 & 生成密钥 */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; - await publicGenKeyFunc(aliasString, options); - - /* 集成证书参数集 */ - let attestProperties = new Array(); - attestProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - attestProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - attestProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - attestProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - attestProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_UDID, - value: udid - }; - attestProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SERIAL, - value: serial - }; - attestProperties[6] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_DEVICE, - value: deviceId - }; - let huksOptions = { - properties: attestProperties - }; - - await publicAttestKey(aliasString, huksOptions); - - await publicDeleteKeyFunc(aliasString, options); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testAttestId') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testAttestId(); - }) - } - .width('100%') - .height('100%') - } +async function testSm4Cipher() { + encryptOptions.inData = StringToUint8Array(cipherInData); + /* 传入认证令牌 */ + await publicUpdateFunc(handle, fingerAuthToken, encryptOptions); + encryptUpdateResult = updateResult; + + encryptOptions.inData = new Uint8Array(new Array()); + /* 传入认证令牌 */ + await publicFinishFunc(handle, fingerAuthToken, encryptOptions); + if (finishOutData === cipherInData) { + console.info('test finish encrypt err '); + } else { + console.info('test finish encrypt success'); + } } ``` -### AttestKey - -应用生成非对称密钥后,可以通过Key attestation获取证书链。应用还可以通过id attestation获取证书链,其中公证书带有设备id等信息。 - -ID Attestation和Key Attestation只有拥有TEE环境的设备才具备该功能。 - -开发步骤如下: +## 密钥证明 -1. 生成证书。 -2. 获取证书信息。 +HUKS为密钥提供合法性证明能力,主要应用于非对称密钥的公钥的证明。基于PKI证书链技术,HUKS可以为存储在HUKS中的非对称密钥对的公钥签发证书,证明其公钥的合法性。业务可以通过OpenHarmony提供的根CA证书,逐级验证HUKS签发的密钥证明证书,来确保证书中的公钥以及对应的私钥,确实来自合法的硬件设备,且存储管理在HUKS中。 -**支持的密钥类型:** +**开发流程** +1. 指定密钥别名和需要证明的密钥属性的标签传入HUKS。 +2. 调用HUKS为应用生成一个依次由根CA证书、设备CA证书、设备证书、密钥证书组成的X.509证书链。 +3. 将证书链传输至受信任的服务器,并在服务器上解析和验证证书链的有效性和单个证书是否吊销。 -RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, X25519 +**接口说明** -> **说明** -> -> 存储的 keyAlias 密钥别名最大为64字节 +**表7** 密钥认证接口介绍 +| 接口名 | 描述 | +| -------------------------------------- | ----------------------------| +|attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| 密钥认证| -在使用示例前,需要先了解几个预先定义的变量: +**开发步骤** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------- | ---- | ------------------------------------ | -| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 | -| options | HuksOptions | 是 | 用于获取证书时指定所需参数与数据。 | +```ts +/* + * 以下以attestKey Callback接口操作验证为例 + */ +import huks from '@ohos.security.huks'; -关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let keyAliasString = "key attest"; +let aliasString = keyAliasString; +let aliasUint8 = StringToUint8Array(keyAliasString); +let securityLevel = StringToUint8Array('sec_level'); +let challenge = StringToUint8Array('challenge_data'); +let versionInfo = StringToUint8Array('version_info'); +let attestCertChain; -**示例:** +let genKeyProperties = new Array(); +genKeyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA +}; +genKeyProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT +}; +genKeyProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 +}; +genKeyProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +genKeyProperties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +genKeyProperties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS +}; +genKeyProperties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT +}; +genKeyProperties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let genOptions = { + properties: genKeyProperties +}; -```ts -/* 证书AttestKey操作示例如下*/ -import huks from '@ohos.security.huks'; +let attestKeyproperties = new Array(); +attestKeyproperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel +}; +attestKeyproperties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge +}; +attestKeyproperties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo +}; +attestKeyproperties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 +}; +let huksOptions = { + properties: attestKeyproperties +}; function StringToUint8Array(str) { let arr = []; @@ -3477,22 +2583,7 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { @@ -3503,27 +2594,33 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback attestKeyItem`); +async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await attestKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`); + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise{ +function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise{ return new Promise((resolve, reject) => { try { huks.attestKeyItem(keyAlias, huksOptions, function (error, data) { @@ -3534,137 +2631,49 @@ function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise< } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); +async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback attestKeyItem`); + let throwObject = {isThrow: false}; try { - await deleteKeyItem(keyAlias, huksOptions) + await attestKeyItem(keyAlias, huksOptions, throwObject) .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`); + if (data !== null && data.certChains !== null) { + attestCertChain = data.certChains; + } }) .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); +async function AttestKeyTest() { + await publicGenKeyFunc(aliasString, genOptions); + + await publicAttestKey(aliasString, huksOptions); + console.info('attest certChain data: ' + attestCertChain) } +``` -let securityLevel = StringToUint8Array('sec_level'); -let challenge = StringToUint8Array('challenge_data'); -let versionInfo = StringToUint8Array('version_info'); -let keyAliasString = "key attest"; +> 常见问题 -async function testAttestKey() { - let aliasString = keyAliasString; - let aliasUint8 = StringToUint8Array(aliasString); - - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; - await publicGenKeyFunc(aliasString, options); - - /* 集成证书参数集 */ - let attestProperties = new Array(); - attestProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - attestProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - attestProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - attestProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let huksOptions = { - properties: attestProperties - }; +1. Cannot find name 'huks'. - await publicAttestKey(aliasString, huksOptions); + 不能找到huks,使用了接口函数但没导入security.huks.d.ts,添加import huks from '@ohos.security.huks';即可。 - await publicDeleteKeyFunc(aliasString, options); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testAttestKey') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testAttestKey(); - }) - } - .width('100%') - .height('100%') - } -} -``` +2. Property 'finishSession' does not exist on type 'typeof huks'. Did you mean 'finish'? + 不能在huks库中找到finishSession,finishSession是API9版本的,请更新SDK版本或替换新版本的security.huks.d.ts文件。 \ No newline at end of file diff --git a/zh-cn/application-dev/security/huks-overview.md b/zh-cn/application-dev/security/huks-overview.md index 0dbdb097edb71bf32738f6f26ad3b002b740e704..a9e2b8411c9f01972ba4566643c83ab2903e59b4 100755 --- a/zh-cn/application-dev/security/huks-overview.md +++ b/zh-cn/application-dev/security/huks-overview.md @@ -1,28 +1,75 @@ -# HUKS开发概述 +# 通用密钥库开发概述 -## 功能简介 +## 简介 + +OpenHarmony通用密钥库系统(英文全称:Open**H**armony **U**niversal **K**ey**S**tore,以下简称HUKS)是OpenHarmony提供的系统级的密钥管理系统服务,提供密钥的全生命周期管理能力,包括密钥生成、密钥存储、密钥使用、密钥销毁等功能,以及对存储在HUKS中的密钥提供合法性证明。 +HUKS基于系统安全能力,为业务提供密钥全生命周期的安全管理,业务无需自己实现,利用HUKS的系统能力,就能确保业务密钥的安全。 + + +以下目录文档主要介绍了HUKS在典型场景下的用法、原理以及支持的密码算法规格。 + +- [生成新密钥](huks-guidelines.md#生成新密钥) +- [导入外部密钥](huks-guidelines.md#导入外部密钥) +- [常见密钥操作](huks-guidelines.md#常见密钥操作) +- [密钥访问控制](huks-guidelines.md#密钥访问控制) +- [密钥证明](huks-guidelines.md#密钥证明) +- [支持的算法类型及参数组合](huks-appendix.md#支持的算法类型及参数组合) +- [密钥材料格式](huks-appendix.md#密钥材料格式) -HUKS(OpenHarmony Universal KeyStore)向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成。 ## 基本概念 -- HUKS提供密钥管理功能,支持的主要操作包括:加密解密、签名验签、派生协商密钥、计算HMAC(Hash-based Message Authentication Code)。 -- HUKS涉及的算法主要有:AES加密解密、RSA加密解密、RSA签名验签、ECC签名验签、DSA签名验签、ED25519签名验签、PBKDF2派生、DH协商、ECDH协商、X25519协商等。 -- HUKS当前使用的算法库为OpenSSL和mbed TLS。 +在使用HUKS开发之前,建议了解以下基本概念: + +- **HUKS Core** + + HUKS核心组件,承载HUKS的核心功能,包括密钥的密码学运算、明文密钥的加解密、密钥访问控制等。一般运行在设备的安全环境中(如TEE、安全芯片等,不同的厂商有所不同),保证密钥明文不出HUKS Core。 + + +- **密钥会话** + + 应用通过指定密钥别名,给当前操作的密钥建立一个会话,HUKS为每个会话生成一个全局唯一的句柄值来索引该会话。它的作用是缓存密钥使用期间的信息,包括操作数据、密钥信息、访问控制属性等。密钥操作一般需要经过**建立会话、传入数据和参数、结束会话(中止会话)** 三个阶段。 + -## 运作机制 +## 实现原理 -HUKS对密钥的使用主要通过InitSession、UpdateSession、FinishSession操作来实现。 -- **InitSession操作**:读取密钥,并为其创建Session Id返回给调用者。 +HUKS的核心安全设计包括以下几点: +- **密钥不出安全环境** -- **UpdateSession操作**:根据InitSession操作获取的Session Id对数据进行分段updateSession处理。 + HUKS的核心特点是密钥全生命周期明文不出HUKS Core,在有硬件条件的设备上,如有TEE(Trusted Execution Environment)或安全芯片的设备,HUKS Core运行在硬件安全环境中。能确保即使REE(Rich Execution Environment)环境被攻破,密钥明文也不会泄露。 +- **系统级安全加密存储** -- **FinishSession操作**:当所有待处理的数据均传入HUKS后,调用FinishSession操作完成最终数据处理,释放资源。 + 基于设备根密钥加密业务密钥,在有条件的设备上,叠加用户口令加密保护密钥。 +- **严格的访问控制** -> **须知:**
-> 当InitSession、UpdateSession、FinishSession操作中的任一阶段发生错误时,都需要调用AbortSession操作来终止密钥的使用。 + 只有合法的业务才有权访问密钥,同时支持用户身份认证访问控制以支持业务的高安敏感场景下安全访问密钥的诉求。 +- **密钥的合法性证明** + 可为业务提供硬件厂商级别的密钥的合法性证明,证明密钥没有被篡改,并确实存在于有硬件保护的HUKS Core中,以及拥有正确的密钥属性。 + + +此外,密钥会话是HUKS中承载密钥使用的基础,它的主要作用是初始化密钥信息、缓存业务数据等。对数据的密码学运算和对密钥密文的加解密都是在HUKS Core中进行,以此保证密钥明文和运算过程的安全。 + +**图1** HUKS运行机制 + +![huks_architect](figures/huks_architect.png) ## 约束与限制 -不涉及。 + + - **基于别名的访问** + + 由于密钥材料不出HUKS的限制,应用只能以别名的方式访问密钥材料,而且密钥的别名必须保证应用内唯一(否则已存在的同别名密钥会被覆盖),长度不能超过64个字节。 + + - **数据分片大小限制** + + 所有数据需要经过IPC通道传输到HUKS,受IPC缓冲区大小限制,建议对总大小超过100K的数据进行分片传输,且分片大小不超过100K。 + + - **指定必选参数** + + 在**生成密钥或导入密钥时**,必须指定密码算法、密钥大小和使用目的参数,其他参数可选(如工作模式、填充模式、散列算法等),但是在**使用密钥**时必须传入密码算法相关的完整的参数。 + + - **密钥材料格式** + + 导入/导出密钥时(包括密钥对、公钥、私钥),密钥材料的数据格式必须满足HUKS要求的格式,具体各个密码算法密钥材料见[密钥材料格式](huks-appendix.md#密钥材料格式)。 +