多种加密方式实现加解密

多种加密方式实现加解密

HarmonyOS
2024-05-21 20:39:21
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
flyCloud00

1.单框架iv参数目前只支持12位 ,java服务的iv参数设置为16位。

解决方式: 1.修改java接口;2.提需求给单框架,使其支持16位。

2.java服务默认没有设置 AAD参数,而当框架demo默认为 byte[] aad =[0, 0, 0, 0, 0, 0, 0, 0]。

解决方式:需要手动设置单框架的aad为null。

 * 字符串转Uint8Array 
 * 
 * @param str 字符串 
 * @returns Uint8Array

使用的核心API

1. Unit8Array

2. Base64。

核心代码解释

/** 
 * base64加密 
 * Uint8Array->string 
 * 
 * @param src Uint8Array 
 * @param options BASIC or MIME 
 * @returns string 
 */
import cryptoFramework from '@ohos.security.cryptoFramework'; 
import util from '@ohos.util'; 
 
const TAG = "EncryptUtil"; 
 
/** 
 * AES加密 
 */ 
export class EncryptUtils { 
  private static cipherAlgName = 'AES|GCM|NoPadding'; 
 
  /** 
   * 
   * @param data 文明 
   * @param keyString 秘钥 
   * @param ivParameter 偏移量 
   * @returns 密文+16长度的authTag 
   */ 
  public static async encrypt(data: Uint8Array, keyString: string, ivParameter: string): Promise<cryptoFramework.DataBlob> { 
    try { 
      let symKey: cryptoFramework.SymKey = await EncryptUtils.getSymKeyByKey(keyString); 
      // mode为加密 
      let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE 
      let base64Helper = new util.Base64Helper(); 
      let iv = base64Helper.decodeSync(ivParameter, util.Type.BASIC) 
      let genGcmParamsSpec: cryptoFramework.GcmParamsSpec = EncryptUtils.genGcmParamsSpec(iv, null, null); 
      let cipher: cryptoFramework.Cipher = await EncryptUtils.createAndInitCipher(symKey, mode, genGcmParamsSpec); 
      let dataBlob: cryptoFramework.DataBlob = { data: data } 
      // 返回 密文+16长度的authTag 
      return cipher.doFinal(dataBlob); 
    } catch (error) { 
      console.log(TAG, "encrypt is failed: " + error); 
      throw new Error("encrypt is failed: " + error); 
    } 
  } 
 
  /** 
   * 对字符串进行加密 
   * 
   * @param str 明文 
   * @param keyString 秘钥 
   * @param ivParameter iv 
   */ 
  public static async encryptString(str: string, keyString: string, ivParameter: string): Promise<string> { 
    let dataBlob = await EncryptUtils.encrypt(EncryptUtils.stringToUint8Array(str), keyString, ivParameter); 
    return EncryptUtils.base64dEncodeSync(dataBlob.data); 
  } 
 
  /** 
   * 解密 
   * 
   * @param data 密文+16字节的authTag 
   * @param keyString 秘钥 
   * @returns Promise<cryptoFramework.DataBlob>  解密后的数组 
   */ 
  public static async decrypt(data: Uint8Array, keyString: string, ivParameter: string): Promise<cryptoFramework.DataBlob> { 
    let symKey: cryptoFramework.SymKey = await EncryptUtils.getSymKeyByKey(keyString); 
    let base64Helper = new util.Base64Helper(); 
    let iv = base64Helper.decodeSync(ivParameter, util.Type.BASIC) 
    // 密文 
    let cipherText = data.subarray(0, data.length - 16); 
    // authTag 
    let authTag = data.subarray(data.length - 16, data.length); 
    let gcmParamsSpec: cryptoFramework.GcmParamsSpec = EncryptUtils.genGcmParamsSpec(iv, authTag, null); 
    let decryptMode = cryptoFramework.CryptoMode.DECRYPT_MODE 
    let cipher: cryptoFramework.Cipher = await EncryptUtils.createAndInitCipher(symKey, decryptMode, gcmParamsSpec); 
    return cipher.doFinal({ data: cipherText }); 
  } 
 
  /** 
   * 对字符串进行解密 
   * 
   * @param str 密文 
   * @param keyString 秘钥 
   * @param ivParameter iv 
   */ 
  public static async decryptString(str: string, keyString: string, ivParameter: string): Promise<string> { 
    try { 
      let dataBlob = await EncryptUtils.decrypt(EncryptUtils.base64dDecodeSync(str), keyString, ivParameter); 
      let sre = EncryptUtils.uint8ArrayToString(dataBlob.data); 
      return sre; 
    } catch (e) { 
      console.log(TAG, e); 
      return null; 
    } 
  } 
 
  /** 
   * 将string类型的秘钥转为SymKey对象 
   * 
   * @param keyString 对称秘钥, 该值从云端获取,根据该秘钥进行加密,云端根据此秘钥进行解密 
   * @returns Promise<cryptoFramework.SymKey> 
   */ 
  private static async getSymKeyByKey(keyString: string): Promise<cryptoFramework.SymKey> { 
    try { 
      let base64Helper = new util.Base64Helper; 
      let dataUint8Array = base64Helper.decodeSync(keyString) 
      // AES256对应的数组长度为32位 AES192=24位 
      let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES256"); 
      return symKeyGenerator.convertKey({ data: dataUint8Array }); 
    } catch (error) { 
      //log.error(TAG, "getSymKeyByKey is failed: " + error) 
      console.log("getSymKeyByKey is failed: " + error) 
    } 
  } 
 
  /** 
   * 随机生成SymKey 
   * 
   * @param symAlgName 算法名称 
   * 
   * @returns Promise<SymKey> 
   */ 
  public static async generateSymKey(symAlgName: string): Promise<cryptoFramework.SymKey> { 
    let symKeyGenerator = await cryptoFramework.createSymKeyGenerator(symAlgName); 
    return symKeyGenerator.generateSymKey(); 
  } 
 
  /** 
   * 获取对称秘钥 
   * 
   * @param symKey symKey对象 
   * @returns 
   */ 
  public static async getKeyStringBySymKey(symKey: cryptoFramework.SymKey) { 
    let dataBlob: cryptoFramework.DataBlob = symKey.getEncoded(); 
    return EncryptUtils.uint8ArrayToString(dataBlob.data); 
  } 
 
  /** 
   * 创建并初始化cipher 
   * 
   * @param symKey SymKey对象 
   * @param mode 加密/解密 
   * @param gcmParamsSpec gcmParamsSpec 
   * @returns cipher 
   */ 
  private static async createAndInitCipher(symKey: cryptoFramework.SymKey, mode: cryptoFramework.CryptoMode, gcmParamsSpec: cryptoFramework.GcmParamsSpec): Promise<cryptoFramework.Cipher> { 
    let cipher: cryptoFramework.Cipher = cryptoFramework.createCipher(EncryptUtils.cipherAlgName); 
    await cipher.init(mode, symKey, gcmParamsSpec); 
    return cipher; 
  } 
 
  /** 
   * 获取genGcmParamsSpec 
   * 
   * @param iv 目前只支持12位 
   * @param authTag 认证tag 
   * @param aad aad java默认为null 
   * @returns 
   */ 
  private static genGcmParamsSpec(iv: Uint8Array, authTag: Uint8Array, aad: Uint8Array): cryptoFramework.GcmParamsSpec { 
    let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 
      iv: { data: iv }, 
      aad: aad === null ? null : { data: aad }, 
      authTag: authTag === null ? null : { data: authTag }, 
      algName: "GcmParamsSpec" 
    }; 
    return gcmParamsSpec; 
  } 
 
  /** 
   * 字符串转Uint8Array 
   * 
   * @param str 字符串 
   * @returns Uint8Array 
   */ 
  private static stringToUint8Array(str: string): Uint8Array { 
    let arr: Uint8Array = new Uint8Array(str.length); 
    for (let i = 0, j = str.length; i < j; ++i) { 
      arr[i] = str.charCodeAt(i); 
    } 
    return arr; 
  } 
 
  /** 
   * Uint8Array转字符串 
   * 
   * @param str Uint8Array 
   * @returns string 
   */ 
  private static uint8ArrayToString(array: Uint8Array): string { 
    let arrayString: string = ''; 
    for (let i = 0; i < array.length; i++) { 
      arrayString += String.fromCharCode(array[i]); 
    } 
    return arrayString; 
  } 
 
  /** 
   * base64 解密 
   * string -> Uint8Array 
   * 
   * @param src string 
   * @param options BASIC or MIME 
   * @returns Uint8Array 
   */ 
  public static base64dDecodeSync(src: string, options?: util.Type): Uint8Array { 
    let base64Helper = new util.Base64Helper(); 
    return base64Helper.decodeSync(src, options); 
  } 
 
  /** 
   * base64加密 
   * Uint8Array->string 
   * 
   * @param src Uint8Array 
   * @param options BASIC or MIME 
   * @returns string 
   */ 
  public static base64dEncodeSync(src: Uint8Array, options?: util.Type): string { 
    let base64Helper = new util.Base64Helper(); 
    return base64Helper.encodeToStringSync(src, options); 
  } 
}

适配的版本信息

IDE:DevEco Studio 4.0.1.501

SDK:HarmoneyOS 4.0.0.8

分享
微博
QQ
微信
回复
2024-05-22 16:19:18
相关问题
RSA导入外部密钥实现加解密
393浏览 • 1回复 待解决
实现一次非对称RSA非对称加解密
476浏览 • 1回复 待解决
加解密算法库框架使用
491浏览 • 1回复 待解决
基于加解密算法框架的规格问题
228浏览 • 1回复 待解决
SM4采用OFB模式进行加解密
352浏览 • 1回复 待解决
如何进行不同规格的AES加解密
248浏览 • 1回复 待解决
求大佬告知如何进行des加解密
551浏览 • 1回复 待解决
AES加解密长字符串是否需要分段
187浏览 • 1回复 待解决
如何使用SM4的CBC模式加解密
200浏览 • 1回复 待解决
使用32字节秘钥加解密后报错
605浏览 • 1回复 待解决
加解密HmacSha1 、HmacSha256、aes参考Demo
661浏览 • 1回复 待解决
如何使用国密SM2算法进行加解密
1025浏览 • 1回复 待解决
SM4 CBC模式加解密,有好的方案吗?
480浏览 • 1回复 待解决