HarmonyOS 鸿蒙Next 有没有API12的3DES加密算法demo?

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

HarmonyOS 鸿蒙Next 有没有API12的3DES加密算法demo?

请问有没有API12的3DES加密算法demo?

2 回复

鸿蒙原生cryptoFramework密钥库支持3DES加解密 但是密钥仅支持24字节 192位

3des规格: 【 https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/crypto-sym-encrypt-decrypt-spec-V5#section3des

以下为 鸿蒙原生 3DES192|CBC|PKCS5 的demo

import { cryptoFramework } from '@kit.CryptoArchitectureKit';

import { buffer, util } from '@kit.ArkTS';

[@Entry](/user/Entry)

[@Component](/user/Component)

struct TDes3Crypto {

  [@State](/user/State) message: string = '点击开始';

  build() {

    Row() {

      Column() {

        Text(this.message)

          .fontSize(50)

          .fontWeight(FontWeight.Bold)

          .onClick(() => {

            DES3Crypto()

          })

      }

      .width('100%')

    }

    .height('100%')

  }

}

// 加密消息

function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {

  let cipher = cryptoFramework.createCipher('3DES192|CBC|PKCS5');

  let iv = genIvParamsSpec();

  cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv);

  let encryptData = cipher.doFinalSync(plainText);

  return encryptData;

}

// 解密消息

function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {

  let decoder = cryptoFramework.createCipher('3DES192|CBC|PKCS5');

  let iv = genIvParamsSpec();

  decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv);

  let decryptData = decoder.doFinalSync(cipherText);

  return decryptData;

}

function genSymKeyByData(symKeyData: Uint8Array) {

  let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };

  let symGenerator = cryptoFramework.createSymKeyGenerator('3DES192');

  let symKey = symGenerator.convertKeySync(symKeyBlob);

  console.info('convertKey success');

  return symKey;

}

function genIvParamsSpec() {

  let iv = new Uint8Array(buffer.from('01234567', 'utf-8').buffer);

  console.error("iv  "+iv)

  // let arr =  [0, 1, 2, 3, 4, 5, 6, 7, 8]; ; // 8 bytes

  let dataIv = new Uint8Array(iv);

  let ivBlob: cryptoFramework.DataBlob = { data: dataIv };

  let ivParamsSpec: cryptoFramework.IvParamsSpec = {

    algName: "IvParamsSpec",

    iv: ivBlob

  };

  return ivParamsSpec;

}

function DES3Crypto() {

  let base64 = new util.Base64Helper()

  let key = "neusofteducationplatform";

  let u8a = new Uint8Array(buffer.from(key, 'utf-8').buffer)

  // let deBaseKey = base64.decodeSync(key)

  // let keyData = new Uint8Array([238, 249, 61, 55, 128, 220, 183, 224, 139, 253, 248, 239, 239, 41, 71, 25, 235, 206, 230, 162, 249, 27, 234, 114]);

  let symKey = genSymKeyByData(u8a);

  let str: string = "好不好嘛  可不可以呀  test  !@#$%^&*()";

  let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(str, 'utf-8').buffer) };

  let encryptText = encryptMessage(symKey, plainText);

  let base64en = base64.encodeToStringSync(encryptText.data)

  console.info('decrypt ok      '+ base64en) ;

  // let encryptoMes: cryptoFramework.DataBlob = { data: new Uint8Array(encryptoMessage) };

  let decryptText = decryptMessage(symKey, encryptText);

  console.info('decrypt ok');

  console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));

  /*if (plainText.data.toString() === decryptText.data.toString()) {

    console.info('decrypt ok');

    console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));

  } else {

    console.error('decrypt failed');

  }*/

}

如果使用的密钥并不为24字节 192位 目前只能使用三方库 @ohos/crypto-js

三方库 crypto-js 参考链接 : 【 https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Fcrypto-js 】

import CryptoJS from '[@ohos](/user/ohos)/crypto-js'

[@Entry](/user/Entry)

[@Component](/user/Component)

struct TDes3Crypto {

  [@State](/user/State) message: string = '点击开始';

  build() {

    Row() {

      Column() {

        Text(this.message)

          .fontSize(50)

          .fontWeight(FontWeight.Bold)

          .onClick(() => {

            DES3Crypto()

          })

      }

      .width('100%')

    }

    .height('100%')

  }

}

function DES3Crypto() {

  let str: string = "202412345678";

  let key: string = "";  //您的密钥

  // let UTF8key: string = CryptoJS.enc.Hex.parse(key);

  let newUTF8key: string = CryptoJS.enc.Utf8.parse(key);

  let encrypted: string = CryptoJS.TripleDES.encrypt(str, newUTF8key, {

    mode: CryptoJS.mode.ECB,

    // mode: CryptoJS.mode.CBC,

    padding: CryptoJS.pad.Pkcs7,

    // iv: CryptoJS.enc.Hex.parse('202012$6')

  }).ciphertext.toString(CryptoJS.enc.Base64);

  console.log("...TripleDES encrypt:" + encrypted);

  let decrypted: string = CryptoJS.TripleDES.decrypt(encrypted, newUTF8key, {

    mode: CryptoJS.mode.ECB,

    // mode: CryptoJS.mode.CBC,

    padding: CryptoJS.pad.Pkcs7,

    // iv: CryptoJS.enc.Hex.parse('202012$6')

  }).toString(CryptoJS.enc.Utf8);

  console.log("...TripleDES decrypt:" + decrypted);

)

  console.log("TripleDES decrypt = " + decrypted);

}

解密的方法只能对 已加密的密文进行解密

加密方法 let encryptText = encryptMessage(symKey, plainText);

encryptText 就是密文 encryptText .data拿到的密文二进制数组 通过以下方法转为 base64 的字符串

let base64en = base64.encodeToStringSync(encryptText.data)

将base64的字符串解密

需要使用 base64.decodeSync()的方法 以下是二进制数组密文解密方法

let decryptText = decryptMessage(symKey, encryptText);

更多关于HarmonyOS 鸿蒙Next 有没有API12的3DES加密算法demo?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


HarmonyOS 鸿蒙Next 提供了丰富的加密算法库,其中包括3DES(Triple DES)加密算法。API 12级别下,你可以使用鸿蒙系统自带的加密API来实现3DES加密。以下是一个简短的3DES加密算法的demo示例,使用鸿蒙的加密库:

#include <crypto/cipher.h>
#include <string>
#include <vector>

std::vector<uint8_t> tripleDesEncrypt(const std::vector<uint8_t>& key, const std::vector<uint8_t>& data) {
    Cipher cipher;
    cipher.Init(Cipher::ALG_3DES_ECB_NOPADDING, Cipher::MODE_ENCRYPT, key);
    std::vector<uint8_t> output(cipher.GetOutputSize(data.size()));
    size_t len = cipher.DoFinal(data, output.data());
    output.resize(len);
    return output;
}

int main() {
    std::vector<uint8_t> key = {/* 24-byte key for 3DES */};
    std::vector<uint8_t> data = {/* data to encrypt */};
    
    std::vector<uint8_t> encryptedData = tripleDesEncrypt(key, data);
    
    // Use encryptedData as needed
}

注意,此代码是示例性质,需要根据实际项目中的密钥管理、填充方式(如ECB模式可能需要PKCS7填充)和异常处理进行调整。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部