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

HUKS的SM4加解密

HarmonyOS
2024-05-28 21:20:08
浏览
收藏 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%') 
    } 
  
  } 
  
} 
 

实现效果

适配的版本信息

  • IDE:DevEco    Studio 4.0.1.601
  • SDK:HarmoneyOS    4.0.10.11
分享
微博
QQ
微信
回复
2024-05-29 22:28:30
相关问题
如何使用SM4CBC模式加解密
956浏览 • 1回复 待解决
SM4采用OFB模式进行加解密
938浏览 • 1回复 待解决
SM4 CBC模式加解密,有好方案吗?
1039浏览 • 1回复 待解决
HarmonyOS SM2,SM4国密加解密使用demo
283浏览 • 1回复 待解决
RSA导入外部密钥实现加解密
804浏览 • 1回复 待解决
huks密钥库导入自定义密钥
241浏览 • 1回复 待解决
Huks如何导入AES密钥
782浏览 • 1回复 待解决
HarmonyOS HUKS 密钥证明根证书问题
439浏览 • 1回复 待解决
HUKS用户认证通过PIN生成密钥
1031浏览 • 1回复 待解决
HarmonyOS 生成SM2密钥对报错
42浏览 • 1回复 待解决
HarmonyOS SM2密钥对转换失败
615浏览 • 1回复 待解决