HarmonyOS RAS加密,AES加密和解密

HarmonyOS
2024-12-20 13:25:34
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
superinsect

AES加解密:

@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)import { aesDecrypt, aesEncrypt } 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')
    })
  }
            .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')
      })
    }

  • 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.

rsa:

//RSA
import cryptoFramework from '@ohos.security.cryptoFramework';
import util from '@ohos.util';
import buffer from '@ohos.buffer';

/*
 * 非对称密钥对,方便使用,可根据具体情况使用
 * */
export class KeyPair {
  publicKey: string
  privateKey: string
}

const base = new util.Base64Helper();

// 字符串转成字节流
function stringToUint8Array(str: string) {
  return new Uint8Array(buffer.from(str, 'utf-8').buffer);
}

// 字节流转成可理解的字符串
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;
}


export class RSA {
  /**
   * 密钥规格
   */
  static ASY_KEY_NAME_RSA_3072: string = 'RSA1024';
  static ALG_NAME_RSA_3072: string = 'RSA|ECB|PKCS1';
  static priKey: Uint8Array = new Uint8Array(); //用于临时保存
  static pubKey: Uint8Array = new Uint8Array(); //用于临时保存

  public static async do() {
    //生成密钥对
    const keyPair = await this.generateRsaKeyPair()
    let priKey = keyPair.privateKey
    let pubKey = keyPair.publicKey

    pubKey =
      "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMG4+XWQxIuxBIHGtqPPR//Uf0L1EK8RhUXbWfcbZrezqiloErU1fOWptbd8wOvWa+iQivl0oBWtKHdhyoxfZ0agqSINYpZRFpzqaduv9W30no1jMsFJgb2kNkhT3nwlSm4vW27jAxEMvbhFJ5lXyWXPQ3cwmMwJxeOH1s6pfewQIDAQAB";
    //加密
    const message = await this.rsaEncrypt("This is Test 这是测试!", pubKey)
    //解密
    const res = await this.rsaDecrypt(message, priKey)
    console.log(res)
  }

  /*
   * 生成非对称密钥对
   *
   * */
  public static async generateRsaKeyPair(): Promise<KeyPair> {
    let keyPair: KeyPair = new KeyPair();
    try {
      let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(this.ASY_KEY_NAME_RSA_3072);
      const tempKeyPair = await asyKeyGenerator.generateKeyPair();
      keyPair = {
        publicKey: base.encodeToStringSync(tempKeyPair.pubKey.getEncoded().data),
        privateKey: base.encodeToStringSync(tempKeyPair.priKey.getEncoded().data)
      }
    } catch (err) {
      console.error(err)
    }
    return keyPair;
  }


  /*
   * 加密
   * */
  public static async rsaEncrypt(str: string, publicKey: string): Promise<string> {
    let result = '';
    try {
      let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(this.ASY_KEY_NAME_RSA_3072);
      let cipher = cryptoFramework.createCipher(this.ALG_NAME_RSA_3072); //创建一个 Cipher (解密)对象

      /*
       * 引入外部的公钥加密
       * */
      let publicKeyDataBlob = { data: base.decodeSync(publicKey) };

      let keyGenPromise: cryptoFramework.KeyPair = await asyKeyGenerator.convertKey(publicKeyDataBlob, null);
      await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyGenPromise.pubKey, null);
      let put: cryptoFramework.DataBlob = { data: stringToUint8Array(str) };
      const finalRes = await cipher.doFinal(put)
      result = base.encodeToStringSync(finalRes.data);
    } catch (err) {
      console.log(err.message)
    }
    return result;
  }

  /*
   * 解密
   *
   * */
  public static async rsaDecrypt(message: string | Uint8Array, privateKey: string): Promise<string> {
    let result = '';
    try {
      let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(this.ASY_KEY_NAME_RSA_3072);
      const privateKeyDataBlob = { data: base.decodeSync(privateKey) };
      const keyPair = await asyKeyGenerator.convertKey(null, privateKeyDataBlob);
      let cipher = cryptoFramework.createCipher(this.ALG_NAME_RSA_3072); //创建一个 Cipher (解密)对象
      await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null);
      let bytes: Uint8Array = null;
      if (typeof message === 'string') {
        bytes = base.decodeSync(message);
      } else {
        bytes = message;
      }
      const finalRes = await cipher.doFinal({ data: bytes })
      result = uint8ArrayToString(finalRes.data);
    } catch (err) {
      console.error(err.code)
    }
    return result;
  }
}

  • 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.
分享
微博
QQ
微信
回复
2024-12-20 16:24:27
相关问题
HarmonyOS ArkTS中如何使用AES加密和解密
414浏览 • 1回复 待解决
HarmonyOS 加密和解密的方案实现
495浏览 • 1回复 待解决
HarmonyOS AES加密/RSA加密问题
496浏览 • 1回复 待解决
HarmonyOS AES加密
396浏览 • 1回复 待解决
HarmonyOS AES加密相关
409浏览 • 1回复 待解决
HarmonyOS 使用AES加密失败
510浏览 • 1回复 待解决
HarmonyOS AES加密编码问题
354浏览 • 1回复 待解决
HarmonyOS AES CBC加密问题
943浏览 • 1回复 待解决
HarmonyOS AES加密算法demo
604浏览 • 1回复 待解决
如何使用AES ECB 加密方式?
555浏览 • 1回复 待解决
HarmonyOS ZIP文件加密压缩和解压缩
1354浏览 • 1回复 待解决
aes-128加密问题如何实现?
533浏览 • 1回复 待解决
AES 加密问题,有知道的吗?
795浏览 • 1回复 待解决
HarmonyOS AES ECB加密后后台解析失败
310浏览 • 1回复 待解决
多种加密方式实现加解密
1453浏览 • 1回复 待解决
HarmonyOS 私钥加密公钥解密问题
537浏览 • 1回复 待解决