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

发布于 1周前 作者 yibo5220 来自 鸿蒙OS

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

辛苦把以下iOS oc的aes解密翻译成鸿蒙artts语言的实现,谢谢  // 解密 + (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 鸿蒙Next 提供一个aes解密包含iv向量的方式示例或者demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

我用AI给你生成了

import crypto from '[@ohos](/user/ohos).crypto';

import { Base64 } from '[@ohos](/user/ohos).base64';

/**

 * AES-256 解密实现

 * [@param](/user/param) encrypted 需要解密的 Base64 字符串

 * [@param](/user/param) secretKey 密钥的 Base64 字符串

 * [@param](/user/param) ivParameter IV 向量的 Base64 字符串

 * [@returns](/user/returns) 解密后的字符串,如果失败则返回 '{}'

 */

export function AESDecryptBase64(encrypted: string, secretKey: string, ivParameter: string): string {

    try {

        // 将 Base64 字符串转换为 Uint8Array

        const keyBytes: Uint8Array = Base64.decode(secretKey);

        const ivBytes: Uint8Array = Base64.decode(ivParameter);

        const encryptedBytes: Uint8Array = Base64.decode(encrypted);

        // 生成 AES 解密器

        const cipher = crypto.createCipher({

            key: keyBytes, // 密钥

            iv: ivBytes,   // IV 向量

            algorithm: crypto.CipherAlgorithm.AES_256_CBC, // AES 256 CBC 模式

            padding: crypto.Padding.PKCS7, // PKCS7 填充方式

        });

        // 执行解密

        const decryptedData: Uint8Array = cipher.decrypt(encryptedBytes);

        // 将解密后的 Uint8Array 转为字符串

        const decryptedText = new TextDecoder('utf-8').decode(decryptedData);

        return decryptedText;

    } catch (error) {

        console.error("AES 解密失败:", error);

        return "{}";

    }

}

使用示例:

let encryptedText = "your_base64_encrypted_string";

let secretKey = "your_base64_secret_key";

let ivParameter = "your_base64_iv";

let decryptedText = AESDecryptBase64(encryptedText, secretKey, ivParameter);

console.log("解密后的文本: ", decryptedText);

更多关于HarmonyOS 鸿蒙Next 提供一个aes解密包含iv向量的方式示例或者demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


鸿蒙加解密模块示例代码:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/crypto-aes-sym-encrypt-decrypt-gcm-V5

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


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 =

‘MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAtclkSWjItsEHpRtRDNS0zdYZORx3h2fgeALEvnAdx0gKgtu/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) {

<span class="hljs-comment">//5QXzAbJj0TJN9OQNvxFhhw== 这种长度的key使用AES128</span>

<span class="hljs-comment">// let aesGenerator = cryptoFramework.createSymKeyGenerator(AES128);</span>

<span class="hljs-comment">//32字节的key需要使用AES256</span>

<span class="hljs-keyword">let</span> aesGenerator = cryptoFramework.createSymKeyGenerator(AES256);

<span class="hljs-keyword">let</span> cipher = cryptoFramework.createCipher(AES256_PKCS5);

<span class="hljs-keyword">let</span> that = <span class="hljs-keyword">new</span> util.Base64Helper();

<span class="hljs-keyword">let</span> textEncoder = <span class="hljs-keyword">new</span> util.TextEncoder();

<span class="hljs-keyword">let</span> buffer = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">20</span>);

<span class="hljs-keyword">let</span> result = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(buffer);

result = textEncoder.encodeInto(AES_ENCRYPT_KEY);

<span class="hljs-comment">//当 AES_ENCRYPT_KEY为base64类型的字符串是才需要调用下述解码方法</span>

<span class="hljs-comment">// let pubKey = that.decodeSync(AES_ENCRYPT_KEY);</span>

<span class="hljs-keyword">let</span> pubKeyBlob: cryptoFramework.DataBlob = { data: result };

aesGenerator.convertKey(pubKeyBlob, (err, symKey) =&gt; {

  <span class="hljs-keyword">if</span> (err) {

    console.error(<span class="hljs-string">"aesEncrypt convertKey: error."</span> + (err as BusinessError).code);

    <span class="hljs-keyword">return</span>;

  }

  console.log(<span class="hljs-string">"--- symKey: "</span> + symKey);

  <span class="hljs-keyword">let</span> ivData = <span class="hljs-keyword">this</span>.stringToUint8Array(AES_IV_KEY);

  <span class="hljs-keyword">let</span> ivdata: cryptoFramework.DataBlob = { data: ivData }; <span class="hljs-comment">//偏移</span>

  <span class="hljs-keyword">let</span> iv: cryptoFramework.IvParamsSpec = { iv: ivdata, algName: <span class="hljs-string">'IvParamsSpec'</span> }

  <span class="hljs-comment">// cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, { algName: AES_IV_KEY }, (err, data) =&gt; {</span>

  cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv, (err, data) =&gt; {

    <span class="hljs-keyword">let</span> input: cryptoFramework.DataBlob = { data: <span class="hljs-keyword">this</span>.stringToUint8Array(message) };

    cipher.doFinal(input, (err, data) =&gt; {

      Logger.info(TAG, <span class="hljs-string">"EncryptOutPut is "</span> + data.data);

      <span class="hljs-keyword">let</span> result = that.encodeToStringSync(data.data)

      Logger.info(TAG, <span class="hljs-string">"result is "</span> + result);

      callback(result)

    })

  })

})

}

stringToUint8Array(str) {

<span class="hljs-keyword">var</span> arr = [];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>, j = str.length; i &lt; j; ++i) {

  arr.push(str.charCodeAt(i));

}

<span class="hljs-keyword">var</span> tmpArray = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(arr);

<span class="hljs-keyword">return</span> tmpArray;

}

uint8ArrayToString(array: Uint8Array) {

<span class="hljs-keyword">let</span> arrayString = <span class="hljs-string">''</span>;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; array.length; i++) {

  arrayString += <span class="hljs-built_in">String</span>.fromCharCode(array[i]);

}

<span class="hljs-keyword">return</span> arrayString;

}

rsaEncrypt(message: string, callback) {

<span class="hljs-keyword">let</span> rsaGenerator = cryptoFramework.createAsyKeyGenerator(RSA512_PRIMES_2);

<span class="hljs-keyword">let</span> cipher = cryptoFramework.createCipher(RSA512_PKCS1);

<span class="hljs-keyword">let</span> that = <span class="hljs-keyword">new</span> util.Base64Helper();

<span class="hljs-keyword">let</span> pubKey = that.decodeSync(RSA_ENCRYPT_KEY);

<span class="hljs-keyword">let</span> pubKeyBlob: cryptoFramework.DataBlob = { data: pubKey };

rsaGenerator.convertKey(pubKeyBlob, <span class="hljs-literal">null</span>, (err, keyPair) =&gt; {

  <span class="hljs-keyword">if</span> (err) {

    Logger.error(<span class="hljs-string">"convertKey: error."</span> + (err as BusinessError).code);

    <span class="hljs-keyword">return</span>;

  }

  cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, <span class="hljs-literal">null</span>, (err, data) =&gt; {

    <span class="hljs-keyword">let</span> input: cryptoFramework.DataBlob = { data: <span class="hljs-keyword">this</span>.stringToUint8Array(message) };

    cipher.doFinal(input, (err, data) =&gt; {

      Logger.info(TAG, <span class="hljs-string">"EncryptOutPut is "</span> + data.data);

      <span class="hljs-keyword">let</span> result = that.encodeToStringSync(data.data)

      Logger.info(TAG, <span class="hljs-string">"result is "</span> + result);

      callback(result)

    })

  })

})

}

rsaDecrypt(message: string, callback) {

<span class="hljs-keyword">let</span> rsaGenerator = cryptoFramework.createAsyKeyGenerator(RSA512_PRIMES_2);

<span class="hljs-keyword">let</span> cipher = cryptoFramework.createCipher(RSA512_PKCS1);

<span class="hljs-keyword">let</span> that = <span class="hljs-keyword">new</span> util.Base64Helper();

<span class="hljs-keyword">let</span> priKey = that.decodeSync(RSA_DECRYPT_KEY);

<span class="hljs-keyword">let</span> priKeyBlob: cryptoFramework.DataBlob = { data: priKey };

rsaGenerator.convertKey(<span class="hljs-literal">null</span>, priKeyBlob, (err, keyPair) =&gt; {

  <span class="hljs-keyword">if</span> (err) {

    Logger.error(TAG, <span class="hljs-string">"convertKey: error."</span> + (err as BusinessError).code);

    <span class="hljs-keyword">return</span>;

  }

  cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, <span class="hljs-literal">null</span>, (err, data) =&gt; {

    <span class="hljs-keyword">try</span> {

      <span class="hljs-keyword">let</span> newMessage = that.decodeSync(message);

      <span class="hljs-keyword">let</span> input: cryptoFramework.DataBlob = { data: newMessage };

      cipher.doFinal(input, (err, data) =&gt; {

        <span class="hljs-keyword">if</span> (err) {

          Logger.error(TAG, <span class="hljs-string">"cipher doFinal."</span> + (err as BusinessError).code);

          <span class="hljs-keyword">return</span>;

        }

        Logger.info(TAG, <span class="hljs-string">"DecryptOutPut is "</span> + data.data);

        <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">this</span>.uint8ArrayToString(data.data);

        Logger.info(TAG, <span class="hljs-string">"result is "</span> + result);

        callback(result)

      })

    } <span class="hljs-keyword">catch</span> (err) {

      Logger.info(TAG, <span class="hljs-string">"cipher init error: "</span> + (err as BusinessError).code);

      <span class="hljs-keyword">return</span> err;

    }

  })

})

}

aesDecrypt(message: string, callback) {

<span class="hljs-comment">//同加密方法中的描述</span>

<span class="hljs-keyword">let</span> aesGenerator = cryptoFramework.createSymKeyGenerator(AES256);

<span class="hljs-keyword">let</span> cipher = cryptoFramework.createCipher(AES256_PKCS5);

<span class="hljs-keyword">let</span> that = <span class="hljs-keyword">new</span> util.Base64Helper();

<span class="hljs-keyword">let</span> textEncoder = <span class="hljs-keyword">new</span> util.TextEncoder();

<span class="hljs-keyword">let</span> buffer = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">20</span>);

<span class="hljs-keyword">let</span> result = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(buffer);

result = textEncoder.encodeInto(AES_ENCRYPT_KEY);

<span class="hljs-comment">//dT/MzvKuG2VSsp+h62E/yQ==</span>

<span class="hljs-keyword">let</span> pubKeyBlob: cryptoFramework.DataBlob = { data: result };

aesGenerator.convertKey(pubKeyBlob, (err, symKey) =&gt; {

  <span class="hljs-keyword">if</span> (err) {

    console.error(<span class="hljs-string">"aesDecrypt convertKey: error."</span> + (err as BusinessError).code);

    <span class="hljs-keyword">return</span>;

  }

  <span class="hljs-keyword">let</span> ivData = <span class="hljs-keyword">this</span>.stringToUint8Array(AES_IV_KEY);

  <span class="hljs-keyword">let</span> ivdata: cryptoFramework.DataBlob = { data: ivData }; <span class="hljs-comment">//偏移</span>

  <span class="hljs-keyword">let</span> iv: cryptoFramework.IvParamsSpec = { iv: ivdata, algName: <span class="hljs-string">'IvParamsSpec'</span> }

  <span class="hljs-comment">// cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null, (err, data) =&gt; {</span>

  cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv, (err, data) =&gt; {

    <span class="hljs-keyword">try</span> {

      <span class="hljs-keyword">let</span> newMessage = that.decodeSync(message);

      <span class="hljs-comment">//测试用</span>

      <span class="hljs-comment">// let newMessage = that.decodeSync('dT/MzvKuG2VSsp+h62E/yQ==');</span>

      <span class="hljs-keyword">let</span> input: cryptoFramework.DataBlob = { data: newMessage };

      cipher.doFinal(input, (err, data) =&gt; {

        <span class="hljs-keyword">if</span> (err) {

          Logger.error(TAG, <span class="hljs-string">"cipher doFinal."</span> + (err as BusinessError).code);

          <span class="hljs-keyword">return</span>;

        }

        Logger.info(TAG, <span class="hljs-string">"DecryptOutPut is "</span> + data?.data);

        <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">this</span>.uint8ArrayToString(data?.data)

        Logger.info(TAG, <span class="hljs-string">"result is "</span> + result);

        callback(result)

      })

    } <span class="hljs-keyword">catch</span> (err) {

      Logger.info(TAG, <span class="hljs-string">"cipher init error: "</span> + (err as BusinessError).code);

      <span class="hljs-keyword">return</span> err;

    }

  })

})

}

}

上面提供的加解密方法的密钥和IV为普通字符串,您的加解密场景是使用的base64格式的字符串,所以加解密出现问题。

提供修改后的CipherModel文件代码如下:

 

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 =

‘MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAtclkSWjItsEHpRtRDNS0zdYZORx3h2fgeALEvnAdx0gKgtu/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_ENCRYPT_KEY: string = ‘ZwGb1EptBYzsMMT2e5ZvMdGMwZ1msuaaAxyV0JpN+6Y=’;

// const AES_IV_KEY: string = ‘xx_aaaa22334_aaa’;//原

const AES_IV_KEY: string = ‘ZXF5bvg0Ne84+R8pAZNmFg==’;

export class CipherModel {

aesEncrypt(message: string, callback) {

<span class="hljs-comment">//5QXzAbJj0TJN9OQNvxFhhw== 这种长度的key使用AES128</span>

<span class="hljs-comment">// let aesGenerator = cryptoFramework.createSymKeyGenerator(AES128);</span>

<span class="hljs-comment">//32字节的key需要使用AES256</span>

<span class="hljs-keyword">let</span> aesGenerator = cryptoFramework.createSymKeyGenerator(AES256);

<span class="hljs-keyword">let</span> cipher = cryptoFramework.createCipher(AES256_PKCS5);

<span class="hljs-keyword">let</span> that = <span class="hljs-keyword">new</span> util.Base64Helper();

<span class="hljs-comment">//密钥为普通字符串</span>

<span class="hljs-comment">// let textEncoder = new util.TextEncoder();</span>

<span class="hljs-comment">// let buffer = new ArrayBuffer(20);</span>

<span class="hljs-comment">// let result = new Uint8Array(buffer);</span>

<span class="hljs-comment">// result = textEncoder.encodeInto(AES_ENCRYPT_KEY);</span>

<span class="hljs-comment">//密钥为base64字符串</span>

<span class="hljs-comment">//当 AES_ENCRYPT_KEY为base64类型的字符串是才需要调用下述解码方法</span>

<span class="hljs-keyword">let</span> result = that.decodeSync(AES_ENCRYPT_KEY);

<span class="hljs-keyword">let</span> pubKeyBlob: cryptoFramework.DataBlob = { data: result };

aesGenerator.convertKey(pubKeyBlob, (err, symKey) =&gt; {

  <span class="hljs-keyword">if</span> (err) {

    console.error(<span class="hljs-string">"aesEncrypt convertKey: error."</span> + (err as BusinessError).code);

    <span class="hljs-keyword">return</span>;

  }

  console.log(<span class="hljs-string">"--- symKey: "</span> + symKey);

  <span class="hljs-comment">//偏移量为base64字符串</span>

  <span class="hljs-keyword">let</span> ivData = that.decodeSync(AES_IV_KEY)

  <span class="hljs-comment">//偏移量为普通字符串</span>

  <span class="hljs-comment">// let ivData = this.stringToUint8Array(AES_IV_KEY);</span>

  <span class="hljs-keyword">let</span> ivdata: cryptoFramework.DataBlob = { data: ivData }; <span class="hljs-comment">//偏移</span>

  <span class="hljs-keyword">let</span> iv: cryptoFramework.IvParamsSpec = { iv: ivdata, algName: <span class="hljs-string">'IvParamsSpec'</span> }

  <span class="hljs-comment">// cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, { algName: AES_IV_KEY }, (err, data) =&gt; {</span>

  cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv, (err, data) =&gt; {

    <span class="hljs-keyword">let</span> input: cryptoFramework.DataBlob = { data: <span class="hljs-keyword">this</span>.stringToUint8Array(message) };

    cipher.doFinal(input, (err, data) =&gt; {

      Logger.info(TAG, <span class="hljs-string">"EncryptOutPut is "</span> + data.data);

      <span class="hljs-keyword">let</span> result = that.encodeToStringSync(data.data)

      Logger.info(TAG, <span class="hljs-string">"result is "</span> + result);

      callback(result)

    })

  })

})

}

stringToUint8Array(str) {

<span class="hljs-keyword">var</span> arr = [];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>, j = str.length; i &lt; j; ++i) {

  arr.push(str.charCodeAt(i));

}

<span class="hljs-keyword">var</span> tmpArray = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(arr);

<span class="hljs-keyword">return</span> tmpArray;

}

uint8ArrayToString(array: Uint8Array) {

<span class="hljs-keyword">let</span> arrayString = <span class="hljs-string">''</span>;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; array.length; i++) {

  arrayString += <span class="hljs-built_in">String</span>.fromCharCode(array[i]);

}

<span class="hljs-keyword">return</span> arrayString;

}

rsaEncrypt(message: string, callback) {

<span class="hljs-keyword">let</span> rsaGenerator = cryptoFramework.createAsyKeyGenerator(RSA512_PRIMES_2);

<span class="hljs-keyword">let</span> cipher = cryptoFramework.createCipher(RSA512_PKCS1);

<span class="hljs-keyword">let</span> that = <span class="hljs-keyword">new</span> util.Base64Helper();

<span class="hljs-keyword">let</span> pubKey = that.decodeSync(RSA_ENCRYPT_KEY);

<span class="hljs-keyword">let</span> pubKeyBlob: cryptoFramework.DataBlob = { data: pubKey };

rsaGenerator.convertKey(pubKeyBlob, <span class="hljs-literal">null</span>, (err, keyPair) =&gt; {

  <span class="hljs-keyword">if</span> (err) {

    Logger.error(<span class="hljs-string">"convertKey: error."</span> + (err as BusinessError).code);

    <span class="hljs-keyword">return</span>;

  }

  cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, <span class="hljs-literal">null</span>, (err, data) =&gt; {

    <span class="hljs-keyword">let</span> input: cryptoFramework.DataBlob = { data: <span class="hljs-keyword">this</span>.stringToUint8Array(message) };

    cipher.doFinal(input, (err, data) =&gt; {

      Logger.info(TAG, <span class="hljs-string">"EncryptOutPut is "</span> + data.data);

      <span class="hljs-keyword">let</span> result = that.encodeToStringSync(data.data)

      Logger.info(TAG, <span class="hljs-string">"result is "</span> + result);

      callback(result)

    })

  })

})

}

rsaDecrypt(message: string, callback) {

<span class="hljs-keyword">let</span> rsaGenerator = cryptoFramework.createAsyKeyGenerator(RSA512_PRIMES_2);

<span class="hljs-keyword">let</span> cipher = cryptoFramework.createCipher(RSA512_PKCS1);

<span class="hljs-keyword">let</span> that = <span class="hljs-keyword">new</span> util.Base64Helper();

<span class="hljs-keyword">let</span> priKey = that.decodeSync(RSA_DECRYPT_KEY);

<span class="hljs-keyword">let</span> priKeyBlob: cryptoFramework.DataBlob = { data: priKey };

rsaGenerator.convertKey(<span class="hljs-literal">null</span>, priKeyBlob, (err, keyPair) =&gt; {

  <span class="hljs-keyword">if</span> (err) {

    Logger.error(TAG, <span class="hljs-string">"convertKey: error."</span> + (err as BusinessError).code);

    <span class="hljs-keyword">return</span>;

  }

  cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, <span class="hljs-literal">null</span>, (err, data) =&gt; {

    <span class="hljs-keyword">try</span> {

      <span class="hljs-keyword">let</span> newMessage = that.decodeSync(message);

      <span class="hljs-keyword">let</span> input: cryptoFramework.DataBlob = { data: newMessage };

      cipher.doFinal(input, (err, data) =&gt; {

        <span class="hljs-keyword">if</span> (err) {

          Logger.error(TAG, <span class="hljs-string">"cipher doFinal."</span> + (err as BusinessError).code);

          <span class="hljs-keyword">return</span>;

        }

        Logger.info(TAG, <span class="hljs-string">"DecryptOutPut is "</span> + data.data);

        <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">this</span>.uint8ArrayToString(data.data);

        Logger.info(TAG, <span class="hljs-string">"result is "</span> + result);

        callback(result)

      })

    } <span class="hljs-keyword">catch</span> (err) {

      Logger.info(TAG, <span class="hljs-string">"cipher init error: "</span> + (err as BusinessError).code);

      <span class="hljs-keyword">return</span> err;

    }

  })

})

}

aesDecrypt(message: string, callback) {

<span class="hljs-comment">//同加密方法中的描述</span>

<span class="hljs-keyword">let</span> aesGenerator = cryptoFramework.createSymKeyGenerator(AES256);

<span class="hljs-keyword">let</span> cipher = cryptoFramework.createCipher(AES256_PKCS5);

<span class="hljs-keyword">let</span> that = <span class="hljs-keyword">new</span> util.Base64Helper();

<span class="hljs-comment">//密钥为普通字符串</span>

<span class="hljs-comment">// let textEncoder = new util.TextEncoder();</span>

<span class="hljs-comment">// let buffer = new ArrayBuffer(20);</span>

<span class="hljs-comment">// // let result = new Uint8Array(buffer);</span>

<span class="hljs-comment">// // result = textEncoder.encodeInto(AES_ENCRYPT_KEY);</span>

<span class="hljs-comment">//密钥为base64字符串</span>

<span class="hljs-keyword">let</span> result = that.decodeSync(AES_ENCRYPT_KEY)

<span class="hljs-comment">//dT/MzvKuG2VSsp+h62E/yQ==</span>

<span class="hljs-keyword">let</span> pubKeyBlob: cryptoFramework.DataBlob = { data: result };

aesGenerator.convertKey(pubKeyBlob, (err, symKey) =&gt; {

  <span class="hljs-keyword">if</span> (err) {

    console.error(<span class="hljs-string">"aesDecrypt convertKey: error."</span> + (err as BusinessError).code);

    <span class="hljs-keyword">return</span>;

  }

  <span class="hljs-comment">//偏移量为普通字符串</span>

  <span class="hljs-comment">// let ivData = this.stringToUint8Array(AES_IV_KEY);</span>

  <span class="hljs-comment">//偏移量为base64字符串</span>

  <span class="hljs-keyword">let</span> ivData = that.decodeSync(AES_IV_KEY)

  <span class="hljs-keyword">let</span> ivdata: cryptoFramework.DataBlob = { data: ivData }; <span class="hljs-comment">//偏移</span>

  <span class="hljs-keyword">let</span> iv: cryptoFramework.IvParamsSpec = { iv: ivdata, algName: <span class="hljs-string">'IvParamsSpec'</span> }

  <span class="hljs-comment">// cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null, (err, data) =&gt; {</span>

  cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv, (err, data) =&gt; {

    <span class="hljs-keyword">try</span> {

      <span class="hljs-keyword">let</span> newMessage = that.decodeSync(message);

      <span class="hljs-comment">//测试用</span>

      <span class="hljs-comment">// let newMessage = that.decodeSync('dT/MzvKuG2VSsp+h62E/yQ==');</span>

      <span class="hljs-keyword">let</span> input: cryptoFramework.DataBlob = { data: newMessage };

      cipher.doFinal(input, (err, data) =&gt; {

        <span class="hljs-keyword">if</span> (err) {

          Logger.error(TAG, <span class="hljs-string">"cipher doFinal."</span> + (err as BusinessError).code);

          <span class="hljs-keyword">return</span>;

        }

        Logger.info(TAG, <span class="hljs-string">"DecryptOutPut is "</span> + data?.data);

        <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">this</span>.uint8ArrayToString(data?.data)

        Logger.info(TAG, <span class="hljs-string">"result is "</span> + result);

        callback(result)

      })

    } <span class="hljs-keyword">catch</span> (err) {

      Logger.info(TAG, <span class="hljs-string">"cipher init error: "</span> + (err as BusinessError).code);

      <span class="hljs-keyword">return</span> err;

    }

  })

})

}

}

在HarmonyOS鸿蒙Next系统中,AES解密操作可以使用系统提供的加密库来实现。以下是一个包含初始化向量(IV)的AES解密示例代码片段:

import java.nio.charset.StandardCharsets;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESDecryption {
    public static String decrypt(String encryptedText, String key, String iv) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(java.util.Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            String encryptedText = "your_base64_encoded_encrypted_text";
            String key = "your_16_byte_key";
            String iv = "your_16_byte_iv";
            String decryptedText = decrypt(encryptedText, key, iv);
            System.out.println("Decrypted Text: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

请注意,密钥(key)和初始化向量(iv)的长度必须为16字节。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!