HUKS的SM4加解密,判断密钥的存在以及删除密钥

HUKS的SM4加解密

HarmonyOS
2024-05-28 21:20:08
1.1w浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
kersin

本文主要介绍使用Huks_SM4对明文进行加解密,判断密钥的存在以及删除密钥。

  • 场景

利用HUKS的系统能力,就能确保业务密钥的安全。

使用的核心API

@ohos.security.huks (通用密钥库系统)

密钥库密钥算法规格

核心代码解释

1.plainText是传入的加密数据;

2.KeyAlias是密钥的别名;

3.设置好SM4的加解密属性参数

核心代码如下:

import huks from '@ohos.security.huks'; 
import { BusinessError } from '@ohos.base'; 
import promptAction from '@ohos.promptAction'; 
  
let KeyAlias = 'KeyAlias'; 
let handle: number; 
let plainText:string = ''; 
let cipherData: Uint8Array; 
let IV = '001122334455'; 
function StringToUint8Array(str: String) { 
  let arr: number[] = new Array(); 
  for (let i = 0, j = str.length; i < j; ++i) { 
    arr.push(str.charCodeAt(i)); 
  } 
  return new Uint8Array(arr); 
} 
  
function Uint8ArrayToString(fileData: Uint8Array) { 
  let dataString = ''; 
  for (let i = 0; i < fileData.length; i++) { 
    dataString += String.fromCharCode(fileData[i]); 
  } 
  return dataString; 
} 
const TAG='Test--'; 
//生成SM4密钥属性信息 
function GetSm4GenerateProperties() { 
  let properties: Array<huks.HuksParam> = new Array(); 
  let index = 0; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 
    value: huks.HuksKeyAlg.HUKS_ALG_SM4 
  }; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 
    value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128 
  }; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_PURPOSE, 
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | 
    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT 
  } 
  return properties; 
} 
  
//SM4加密密钥属性信息 
function GetSm4EncryptProperties() { 
  let properties: Array<huks.HuksParam> = new Array(); 
  let index = 0; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 
    value: huks.HuksKeyAlg.HUKS_ALG_SM4 
  }; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 
    value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128 
  }; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_PURPOSE, 
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT 
  } 
  
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_PADDING, 
    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 
  } 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 
    value: huks.HuksCipherMode.HUKS_MODE_CBC 
  } 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_IV, 
    value: StringToUint8Array(IV) 
  } 
  return properties; 
} 
  
//SM4解密密钥属性信息 
function GetSm4DecryptProperties() { 
  let properties: Array<huks.HuksParam> = new Array(); 
  let index = 0; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 
    value: huks.HuksKeyAlg.HUKS_ALG_SM4 
  }; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 
    value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128 
  }; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_PURPOSE, 
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT 
  } 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_PADDING, 
    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 
  } 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 
    value: huks.HuksCipherMode.HUKS_MODE_CBC 
  } 
   properties[index++] = { 
     tag: huks.HuksTag.HUKS_TAG_IV, 
     value: StringToUint8Array(IV) 
   } 
  return properties; 
} 
  
async function GenerateSm4Key() { 
  let genProperties = GetSm4GenerateProperties(); 
  let options: huks.HuksOptions = { 
    properties: genProperties 
  } 
  await huks.generateKeyItem(KeyAlias, options) 
    .then((data) => { 
  
      console.info(TAG+`callback: generate SM4 Key success, data = ${JSON.stringify(data)}`); 
      AlertDialog.show({message:"generate SM4 Key success"}) 
    }).catch((error: BusinessError) => { 
      console.error(TAG+`callback: generate SM4 Key failed`); 
    }) 
  
} 
  
async function EncryptData() { 
  let encryptProperties = GetSm4EncryptProperties(); 
  let options: huks.HuksOptions = { 
    properties: encryptProperties, 
    inData: StringToUint8Array(plainText) 
  } 
  await huks.initSession(KeyAlias, options) 
    .then((data) => { 
      handle = data.handle; 
    }).catch((error: BusinessError) => { 
      console.error(TAG+`callback: init encryptdata failed`); 
    }) 
  
  await huks.finishSession(handle, options) 
    .then((data) => { 
      AlertDialog.show({message:"加密成功"}) 
      console.info(TAG+`callback: encrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array)); 
      cipherData = data.outData as Uint8Array; 
    }).catch((error: BusinessError) => { 
      console.error(TAG+`callback: encrypt data failed`); 
    }) 
} 
  
async function DecryptData() { 
  let res='' 
  let decryptOptions = GetSm4DecryptProperties(); 
  let options: huks.HuksOptions = { 
    properties: decryptOptions, 
    inData: cipherData 
  } 
  await huks.initSession(KeyAlias, options) 
    .then((data) => { 
      handle = data.handle; 
    }).catch((error: BusinessError) => { 
      console.error(TAG+`callback: init decryptdata failed`); 
    }) 
  await huks.finishSession(handle, options) 
    .then((data) => { 
      res=Uint8ArrayToString(data.outData as Uint8Array); 
      AlertDialog.show({message:'解密成功'}) 
      console.info(TAG+`callback: decrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array)); 
    }).catch((error: BusinessError) => { 
      console.error(TAG+`callback: decrypt data failed`); 
    }) 
  return res; 
} 
  
async function DeleteKey() { 
  let emptyOptions: huks.HuksOptions = { 
    properties: [] 
  } 
  await huks.deleteKeyItem(KeyAlias, emptyOptions) 
    .then((data) => { 
      AlertDialog.show({message:'删除成功'}) 
      console.info(`callback: delete data success`); 
    }).catch((error: BusinessError) => { 
      console.error(`callback: delete data failed`); 
    }) 
} 
  
//检验密钥是否存在的属性信息 
function GetCheckProperties(){ 
  let properties: Array<huks.HuksParam> = new Array(); 
  let index = 0; 
  properties[index++] = { 
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 
    value: huks.HuksKeyAlg.HUKS_ALG_RSA 
  }; 
  return properties; 
  
} 
async function checkKeyPair(){ 
  let decryptOptions = GetCheckProperties() 
  let options: huks.HuksOptions = { 
    properties: decryptOptions, 
    inData: cipherData 
  } 
  huks.isKeyItemExist(KeyAlias, options).then((data) => { 
    promptAction.showToast({ 
      message: "keyAlias: " + KeyAlias +"is existed!", 
      duration: 500, 
    }) 
  }).catch((error: BusinessError)=>{ 
    promptAction.showToast({ 
      message: "find key failed", 
      duration: 6500, 
    }) 
  }) 
} 
  
  
  
@Entry 
@Component 
struct HUKS_SM4 { 
  @State message: string = 'Hello World' 
  @State decryptKeyPair:string=''; 
 // @State encryptStr:string = ""; 
  build() { 
    Row() { 
      Column() { 
        Button('生成密钥') 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .margin({top:100}) 
          .onClick( () => { 
            GenerateSm4Key() 
          }); 
  
        Button('检查密钥是否存在') 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .margin({top:50}) 
          .onClick(()=>{ 
            checkKeyPair(); 
          }); 
  
        TextInput() 
          .border({ 
            width:1 
          }) 
          .margin({top:20}) 
          .width(240) 
          .height(50) 
          .backgroundColor(Color.Pink) 
          .onChange(res=>{ 
            //this.encryptStr = res 
            plainText = res 
            console.info('res',res) 
          }) 
  
        Button('加密') 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .margin({top:30}) 
          .onClick(()=>{ 
            console.info('plainText',plainText) 
           EncryptData(); 
          }); 
  
        Button('解密') 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .margin({top:30}) 
          .onClick(async ()=>{ 
            this.decryptKeyPair=await DecryptData() 
          }); 
        Text(`${this.decryptKeyPair}`) 
          .border({ 
            width:1 
          }) 
          .margin({top:20}) 
          .width(240) 
          .height(50) 
          .backgroundColor(Color.Yellow) 
  
        Button('删除密钥') 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .margin({top:30}) 
          .onClick(()=>{ 
            DeleteKey(); 
          }); 
      } 
      .width('100%') 
    } 
  
  } 
  
} 
 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 241.
  • 242.
  • 243.
  • 244.
  • 245.
  • 246.
  • 247.
  • 248.
  • 249.
  • 250.
  • 251.
  • 252.
  • 253.
  • 254.
  • 255.
  • 256.
  • 257.
  • 258.
  • 259.
  • 260.
  • 261.
  • 262.
  • 263.
  • 264.
  • 265.
  • 266.
  • 267.
  • 268.
  • 269.
  • 270.
  • 271.
  • 272.
  • 273.
  • 274.
  • 275.
  • 276.
  • 277.
  • 278.
  • 279.
  • 280.
  • 281.
  • 282.
  • 283.
  • 284.
  • 285.
  • 286.
  • 287.
  • 288.
  • 289.
  • 290.
  • 291.
  • 292.
  • 293.
  • 294.
  • 295.

实现效果

适配的版本信息

  • IDE:DevEco    Studio 4.0.1.601
  • SDK:HarmoneyOS    4.0.10.11
分享
微博
QQ
微信
回复
2024-05-29 22:28:30


相关问题
HarmonyOS SM2/SM4结合加解密
484浏览 • 1回复 待解决
如何使用SM4CBC模式加解密
1615浏览 • 1回复 待解决
SM4采用OFB模式进行加解密
1498浏览 • 1回复 待解决
SM4 CBC模式加解密,有好方案吗?
1470浏览 • 1回复 待解决
HarmonyOS SM2,SM4国密加解密使用demo
702浏览 • 1回复 待解决
HarmonyOS sm4、rsa等加解密库及参考文档
1107浏览 • 1回复 待解决
RSA导入外部密钥实现加解密
1204浏览 • 1回复 待解决
huks密钥库导入自定义密钥
663浏览 • 1回复 待解决
Huks如何导入AES密钥
1142浏览 • 1回复 待解决
HarmonyOS SM2密钥交换计算协商密钥
301浏览 • 1回复 待解决
HarmonyOS HUKS 密钥证明根证书问题
770浏览 • 1回复 待解决
HarmonyOS SM4如何进行SM4/ECB/NoPadding加密
294浏览 • 1回复 待解决