HarmonyOS 提供一个aes解密包含iv向量的方式示例或者demo

辛苦把以下的aes解密翻译成HarmonyOS arkts语言的实现。

// 解密
+ (NSString *)AESDecryptBase64:(NSString *)encrypted privateKey:(NSString *)secret_key iv:(NSString *)iv_parameter {
  // 密钥、IV向量及需要解密的字符串
  NSData *privateData = [[NSData alloc] initWithBase64EncodedString:secret_key options:NSDataBase64DecodingIgnoreUnknownCharacters];
  NSData *ivData = [[NSData alloc] initWithBase64EncodedString:iv_parameter options:NSDataBase64DecodingIgnoreUnknownCharacters];
  NSData *encryptedData = [[NSData alloc] initWithBase64EncodedString:encrypted options:NSDataBase64DecodingIgnoreUnknownCharacters];

  NSMutableData *key = [NSMutableData dataWithLength:kCCKeySizeAES256];
  [key replaceBytesInRange:NSMakeRange(0, privateData.length) withBytes:[privateData bytes]];

  size_t bufferSize = [encryptedData length] + kCCBlockSizeAES128;
  void *buffer = malloc(bufferSize);

  size_t numBytesDecrypted = 0;
  CCCryptorStatus status = CCCrypt(kCCDecrypt,
    kCCAlgorithmAES,
    kCCOptionPKCS7Padding,
    [key bytes],
  kCCKeySizeAES256,
  [ivData bytes],
  [encryptedData bytes],
  [encryptedData length],
  buffer,
  bufferSize,
    &numBytesDecrypted);

  if (status == kCCSuccess) {
    NSData *decryptedData = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
  } else {
    free(buffer);
    return @"{}";
  }
}
HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

可以先下载官网文档中的示例代码,链接:

https://communityfile-drcn.op.dbankcloud.cn/FileServer/getFile/cmtyPub/011/111/111/0000000000011111111.20240605105421.87085760543017233932108650648019:50001231000000:2800:43DB200C7B6C8A2290D849767226EB7C9F748A21C9F458833A7F520EC17CB9FA.zip?needInitFileName=true

然后将工程中CipherModel文件代码替换成如下代码:

/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { cryptoFramework } from "@kit.CryptoArchitectureKit";
import { buffer, util } from '@kit.ArkTS';
import Logger from './Logger';
import { BusinessError } from '@kit.BasicServicesKit';

const TAG: string = '[CipherModel]'
const RSA_ENCRYPT_KEY: string =
  'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALXJZEloyLbBB6UbUQzUtM3WGTkcd4dn4HgCxL5wHcdICoLbv6EiUjcaQq8c906hqv6/J7Bv9Owj59XMauKweJUCAwEAAQ==';
const RSA_DECRYPT_KEY: string =
  'MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAtcl...................../oSJSNxpCrxz3TqGq/r8nsG/07CPn1cxq4rB4lQIDAQABAkA3boG2IM2TbKj4H6xHTVUUrwRh9dw83eAEuFNl/qoV6c4zRUAx+efZ29rDz6CVWuAhxaVBDUOmOHvyxOL8m8IBAiEA3EcTP1jngtiJ8lffvIVbehM6p7437+9UScKMXZSy/PkCIQDTRFj00GbAW9oKqEWTrUCWNxNFCSR82Mlw1sZvQh5LfQIgBApBrh3BUUMLdKhr8Bc6EEkeAEma2Qm4sAmjbWv2xHECIF81ux1BWj0wZ9hLs2d1Odk4ot+G2kHFdSr8L9tuIbcFAiEA2rEXmzyQTxZM1N4QDkaLJiCwSfMTYu48DxfUcevbfhA=';
const RSA512_PRIMES_2: string = 'RSA512|PRIMES_2';
const RSA512_PKCS1: string = 'RSA512|PKCS1';

const AES128: string = 'AES128';
const AES128_PKCS7: string = 'AES128|PKCS7';

const AES256: string = 'AES256';
const AES256_PKCS5: string = 'AES256|CBC|PKCS5';
// const AES_ENCRYPT_KEY: string = '5QXzAbJj0TJN9OQNvxFhhw==';

// const AES_ENCRYPT_KEY: string = 'xxxx_aaaa22334_aaaa1111-aa11-aaa';
const AES_ENCRYPT_KEY: string = 'xxxx_aaaa22334_aaaa1111-aa11-aaa';


const AES_IV_KEY: string = 'xx_aaaa22334_aaa';

export class CipherModel {
  aesEncrypt(message: string, callback) {
    //5QXzAbJj0TJN9OQNvxFhhw== 这种长度的key使用AES128
    // let aesGenerator = cryptoFramework.createSymKeyGenerator(AES128);

    //32字节的key需要使用AES256
    let aesGenerator = cryptoFramework.createSymKeyGenerator(AES256);
    let cipher = cryptoFramework.createCipher(AES256_PKCS5);

    let that = new util.Base64Helper();


    let textEncoder = new util.TextEncoder();
    let buffer = new ArrayBuffer(20);
    let result = new Uint8Array(buffer);
    result = textEncoder.encodeInto(AES_ENCRYPT_KEY);

    //当 AES_ENCRYPT_KEY为base64类型的字符串是才需要调用下述解码方法
    // let pubKey = that.decodeSync(AES_ENCRYPT_KEY);


    let pubKeyBlob: cryptoFramework.DataBlob = { data: result };
    aesGenerator.convertKey(pubKeyBlob, (err, symKey) => {
      if (err) {
        console.error("aesEncrypt convertKey: error." + (err as BusinessError).code);
        return;
      }
      console.log("--- symKey: " + symKey);
      let ivData = this.stringToUint8Array(AES_IV_KEY);
      let ivdata: cryptoFramework.DataBlob = { data: ivData }; //偏移
      let iv: cryptoFramework.IvParamsSpec = { iv: ivdata, algName: 'IvParamsSpec' }

      // cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, { algName: AES_IV_KEY }, (err, data) => {
      cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv, (err, data) => {
        let input: cryptoFramework.DataBlob = { data: this.stringToUint8Array(message) };
        cipher.doFinal(input, (err, data) => {
          Logger.info(TAG, "EncryptOutPut is " + data.data);
          let result = that.encodeToStringSync(data.data)
          Logger.info(TAG, "result is " + result);
          callback(result)
        })
      })
    })
  }

  stringToUint8Array(str) {
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
      arr.push(str.charCodeAt(i));
    }
    var tmpArray = new Uint8Array(arr);
    return tmpArray;
  }

  uint8ArrayToString(array: Uint8Array) {
    let arrayString = '';
    for (let i = 0; i < array.length; i++) {
      arrayString += String.fromCharCode(array[i]);
    }
    return arrayString;
  }

  rsaEncrypt(message: string, callback) {
    let rsaGenerator = cryptoFramework.createAsyKeyGenerator(RSA512_PRIMES_2);
    let cipher = cryptoFramework.createCipher(RSA512_PKCS1);
    let that = new util.Base64Helper();
    let pubKey = that.decodeSync(RSA_ENCRYPT_KEY);
    let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKey };
    rsaGenerator.convertKey(pubKeyBlob, null, (err, keyPair) => {
      if (err) {
        Logger.error("convertKey: error." + (err as BusinessError).code);
        return;
      }
      cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null, (err, data) => {
        let input: cryptoFramework.DataBlob = { data: this.stringToUint8Array(message) };
        cipher.doFinal(input, (err, data) => {
          Logger.info(TAG, "EncryptOutPut is " + data.data);
          let result = that.encodeToStringSync(data.data)
          Logger.info(TAG, "result is " + result);
          callback(result)
        })
      })
    })
  }

  rsaDecrypt(message: string, callback) {
    let rsaGenerator = cryptoFramework.createAsyKeyGenerator(RSA512_PRIMES_2);
    let cipher = cryptoFramework.createCipher(RSA512_PKCS1);
    let that = new util.Base64Helper();
    let priKey = that.decodeSync(RSA_DECRYPT_KEY);
    let priKeyBlob: cryptoFramework.DataBlob = { data: priKey };
    rsaGenerator.convertKey(null, priKeyBlob, (err, keyPair) => {
      if (err) {
        Logger.error(TAG, "convertKey: error." + (err as BusinessError).code);
        return;
      }
      cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null, (err, data) => {
        try {
          let newMessage = that.decodeSync(message);
          let input: cryptoFramework.DataBlob = { data: newMessage };
          cipher.doFinal(input, (err, data) => {
            if (err) {
              Logger.error(TAG, "cipher doFinal." + (err as BusinessError).code);
              return;
            }
            Logger.info(TAG, "DecryptOutPut is " + data.data);
            let result = this.uint8ArrayToString(data.data);
            Logger.info(TAG, "result is " + result);
            callback(result)
          })
        } catch (err) {
          Logger.info(TAG, "cipher init error: " + (err as BusinessError).code);
          return err;
        }
      })
    })
  }

  aesDecrypt(message: string, callback) {
    //同加密方法中的描述

    let aesGenerator = cryptoFramework.createSymKeyGenerator(AES256);
    let cipher = cryptoFramework.createCipher(AES256_PKCS5);

    let that = new util.Base64Helper();


    let textEncoder = new util.TextEncoder();
    let buffer = new ArrayBuffer(20);
    let result = new Uint8Array(buffer);
    result = textEncoder.encodeInto(AES_ENCRYPT_KEY);

    //dT/MzvKuG2VSsp+h62E/yQ==
    let pubKeyBlob: cryptoFramework.DataBlob = { data: result };
    aesGenerator.convertKey(pubKeyBlob, (err, symKey) => {
      if (err) {
        console.error("aesDecrypt convertKey: error." + (err as BusinessError).code);
        return;
      }

      let ivData = this.stringToUint8Array(AES_IV_KEY);
      let ivdata: cryptoFramework.DataBlob = { data: ivData }; //偏移
      let iv: cryptoFramework.IvParamsSpec = { iv: ivdata, algName: 'IvParamsSpec' }

      // cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null, (err, data) => {
      cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv, (err, data) => {
        try {
          let newMessage = that.decodeSync(message);
          //测试用
          // let newMessage = that.decodeSync('dT/MzvKuG2VSsp+h62E/yQ==');
          let input: cryptoFramework.DataBlob = { data: newMessage };
          cipher.doFinal(input, (err, data) => {
            if (err) {
              Logger.error(TAG, "cipher doFinal." + (err as BusinessError).code);
              return;
            }
            Logger.info(TAG, "DecryptOutPut is " + data?.data);
            let result = this.uint8ArrayToString(data?.data)
            Logger.info(TAG, "result is " + result);
            callback(result)
          })
        } catch (err) {
          Logger.info(TAG, "cipher init error: " + (err as BusinessError).code);
          return err;
        }
      })
    })
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
HarmonyOS能否提供一个NFC识别的demo
431浏览 • 1回复 待解决
提供一个关于地图组件使用demo
596浏览 • 1回复 待解决
能否提供一个关于SM3加密demo
713浏览 • 1回复 待解决
HarmonyOS提供AVRecorder demo示例
30浏览 • 1回复 待解决
HarmonyOS解密方式 AES/ECB/PKCS5Padding
59浏览 • 1回复 待解决
拉起相机或者图库demo提供
261浏览 • 1回复 待解决
提供一个简单示例
2001浏览 • 1回复 待解决
解密HmacSha1 、HmacSha256、aes参考Demo
2220浏览 • 1回复 待解决
需要一个NFC读取demo
697浏览 • 1回复 待解决