HarmonyOS ArkTS中如何使用AES加密和解密

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Excelsior_abit

AES加解密demo:

import { aesEncrypt, aesDecrypt } from './AES128_ECB';

@Entry
@Component
struct Test {
  @State plainText: string = 'Hello World';
  @State plainText1: string = '';
  @State ciphertext1: string = '';
  @State iv: string = '1234564512345645';
  @State keys: string = 'CjZwwvt13DJTTOCD0/z1cw==';
  scroller: Scroller = new Scroller()

  build() {
    Stack({ alignContent: Alignment.TopStart }) {
      Scroll(this.scroller) {
        Column() {
          Text("AES128加解密")
            .fontSize(50)
            .fontWeight(FontWeight.Bold)
          Column() {

            Text("待加密的内容")
              .fontSize(15)
              .fontWeight(FontWeight.Bold)
            TextInput({ text: this.plainText }).onChange((value) => {
              this.plainText = value
            })

            Text("密钥")
              .fontSize(15)
              .fontWeight(FontWeight.Bold)
            TextInput({ text: this.keys }).onChange((value) => {
              this.keys = value
            })

            Text("偏移量")
              .fontSize(15)
              .fontWeight(FontWeight.Bold)
            TextInput({ text: this.iv }).onChange((value) => {
              this.iv = value
            })

            Button("AES128|ECB|PKCS7加密").onClick(async () => {
              this.ciphertext1 = await aesEncrypt(this.plainText, this.keys)
              console.log("aes Encrypt = " + this.ciphertext1);
            })
            TextInput({ text: this.ciphertext1 })

            Button("ECB解密").onClick(async () => {
              this.plainText1 = await aesDecrypt(this.ciphertext1, this.keys)
            })
            TextInput({ text: this.plainText1 })
          }
          .width('100%')
        }
      }
      .scrollable(ScrollDirection.Vertical) // 滚动方向纵向
      .scrollBar(BarState.On) // 滚动条常驻显示
      .scrollBarColor(Color.Gray) // 滚动条颜色
      .scrollBarWidth(10) // 滚动条宽度
      .friction(0.6)
      .edgeEffect(EdgeEffect.None)
      .onScroll((xOffset: number, yOffset: number) => {
        console.info(xOffset + ' ' + yOffset)
      })
      .onScrollEdge((side: Edge) => {
        console.info('To the edge')
      })
      .onScrollStop(() => {
        console.info('Scroll Stop')
      })
    }
  }
}
//AES128_ECB
//加密
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { base, stringToUint8Array, uint8ArrayToString } from './BaseUtil';

export async function aesEncrypt(text:string,puKey:string): Promise<string>{
  let globalResult = ""
  try {
    //这里已AES加解密为例支持AES、SM4、3DES
    let cipherAlgName = 'AES128|ECB|PKCS7';
    // 创建加解密对象
    let globalCipher = cryptoFramework.createCipher(cipherAlgName);
    //这里已AES加解密为例支持AES、SM4、3DES
    let symAlgName = 'AES128';
    //创建密钥对象
    let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
    //将传入的base格式的密钥转为Uint8Array数组
    let dataUint8Array = base.decodeSync(puKey)
    let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array }
    //导入外部密钥
    let promiseSymKey = await symKeyGenerator.convertKey(keyBlob)
    //初始化
    await globalCipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, promiseSymKey, null);
    //加密
    let result = await globalCipher.doFinal({data:stringToUint8Array(text)})
    //将加密结果转换为base64格式,用于保存或者传递
    globalResult = base.encodeToStringSync(result.data);
  } catch (err) {
    console.log(err.message)
  }
  return globalResult;
}

// 解密
export async function aesDecrypt(text: string, key: string) {
  let globalResult = ""
  try {
    //这里已AES加解密为例支持AES、SM4、3DES
    let cipherAlgName = 'AES128|ECB|PKCS7';
    // 创建加解密对象
    let globalCipher = cryptoFramework.createCipher(cipherAlgName);
    //这里已AES加解密为例支持AES、SM4、3DES
    let symAlgName = 'AES128';
    //创建密钥对象
    let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
    //将传入的base格式的密钥转为Uint8Array数组
    let dataUint8Array = base.decodeSync(key)
    let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array }
    //导入外部密钥
    let promiseSymKey = await symKeyGenerator.convertKey(keyBlob)
    await globalCipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, promiseSymKey, null);
    let plainText: cryptoFramework.DataBlob = { data: base.decodeSync(text) }
    let result = await globalCipher.doFinal(plainText)
    //将解密后的结果result解码之后得到明文
    globalResult = uint8ArrayToString(result.data);
    console.log("解密后的明文==》" + globalResult)
  } catch (err) {
    console.log(err.message)
  } finally {
    return globalResult
  }
}

baseutil工具类

import buffer from '@ohos.buffer';
import util from '@ohos.util';

export function uint8ArrayToHexStr(data: Uint8Array): string {
  return buffer.from(data).toString('hex');;
}

//十六进制转Uint8Array
export function HexStrTouint8Array(data: string): Uint8Array {
  return new Uint8Array(buffer.from(data, 'hex').buffer);
}

export const base = new util.Base64Helper();

// 字符串转成字节流
export function stringToUint8Array(str: string) {
  return new Uint8Array(buffer.from(str,'utf-8').buffer);
}
// 字节流转成可理解的字符串
export function uint8ArrayToString(array:Uint8Array) {
  // 将UTF-8编码转换成Unicode编码
  let out: string = "";
  let index: number = 0;
  let len: number = array.length;
  while (index < len) {
    let character = array[index++];
    switch(character >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        out += String.fromCharCode(character);
        break;
      case 12:
      case 13:
        out += String.fromCharCode(((character & 0x1F) << 6) | (array[index++] & 0x3F));
        break;
      case 14:
        out += String.fromCharCode(((character & 0x0F) << 12) | ((array[index++] & 0x3F) << 6) | ((array[index++] & 0x3F) << 0));
        break;
      default:
        break;
    }
  }
  return out;
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS RAS加密AES加密和解密
67浏览 • 1回复 待解决
HarmonyOS 加密和解密的方案实现
35浏览 • 1回复 待解决
如何使用AES ECB 加密方式?
222浏览 • 1回复 待解决
HarmonyOS AES加密
24浏览 • 1回复 待解决
HarmonyOS AES加密相关
30浏览 • 1回复 待解决
HarmonyOS AES解密报错
715浏览 • 1回复 待解决
HarmonyOS AES解密咨询
87浏览 • 1回复 待解决
HarmonyOS AES解密问题
20浏览 • 1回复 待解决
使用AES解密时,一直在报解密异常
347浏览 • 1回复 待解决
HarmonyOS AES CBC加密问题
607浏览 • 1回复 待解决
HarmonyOS AES加密编码问题
83浏览 • 1回复 待解决