小工具知识网

当前位置: 首页 > 行业知识 > 鸿蒙ArkTs 网络请求&AES加解密

行业知识

鸿蒙ArkTs 网络请求&AES加解密

2026-12-02 13:26:34 来源:互联网转载

���年新气象!!!祝大家新年快乐!!龙年大吉!

()

本文基于Api9开发至于为啥用API9 请看关于停用基于鸿蒙Api 8 开发-CSDN博客

正文开始 直接上代码

()

1、参数加密

/** * 请求加密 * @param json 参数 * @param key 秘钥 * @returns {string} 密文 * cipherAlgName 参考https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/cryptoframework-overview-0000001544583933-V2#ZH-CN_TOPIC_0000001573928893__%E5%8A%A0%E8%A7%A3%E5%AF%86%E8%A7%84%E6%A0%BC */function requestEncrypt(json, key = AppConstant.SECRET) {  let cipherAlgName = 'AES256|CBC|PKCS7';  //创建秘钥生成器  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256')    let ivParam: cryptoFramework.IvParamsSpec = {    algName: 'IvParamsSpec',    iv: {      //如果项目需要就将空字符替换      data: stringToUint8Array('', 32)    }  }  let cipher;  //convertKey方法是通过秘钥生成symKey  return symKeyGenerator.convertKey({    data: stringToUint8Array(key)  }).then(symKey => {    try {      //创建cipher      cipher = cryptoFramework.createCipher(cipherAlgName);      console.info(`xx cipher algName: ${cipher.algName}`);    } catch (error) {      console.error(`xx createCipher failed, ${error.code}, ${error.message}`);      return null    }    //创建cipher之后才能初始化    return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ivParam)      .then(() => {        //创建cipher且初始化之后才能执行doFinal        return cipher.doFinal({          data: stringToUint8Array(JSON.stringify(json))        })      })      .then(output => {        let base64 = new util.Base64Helper();        let result = base64.encodeToStringSync(output.data);        return new Promise((resolve) => {          resolve(result)        })      }).catch(e => {        return new Promise((_, reject) => {          reject(e)        })      })  }).catch(e => {    return new Promise((_, reject) => {      reject(e)    })  })}/** *把密钥、明文等转换成输入数据需要的格式 */function stringToUint8Array(str, len = null) {  let arr = [];  if (len == null) {    len = str.length  }  for (let i = 0; i  i) {      arr.push(str.charCodeAt(i))    } else {      arr.push(0)    }  }  return new Uint8Array(arr);}

2、参数解密

/** * 解密 * @param str 密文 * @param key 私钥 * @returns {*|string} 明文 */function decrypt(str, key = AppConstant.SECRET) {  let cipherAlgName = 'AES256|CBC|PKCS7';  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256')  let ivParam: cryptoFramework.IvParamsSpec = {    algName: 'IvParamsSpec',    iv: {      data: stringToUint8Array('', 32)    }  }  let cipher;  return symKeyGenerator.convertKey({    data: stringToUint8Array(key)  }).then(symKey => {    try {      cipher = cryptoFramework.createCipher(cipherAlgName);      console.info(`xx cipher algName: ${cipher.algName}`);    } catch (error) {      console.error(`xx createCipher failed, ${error.code}, ${error.message}`);      return null    }    return cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, ivParam)      .then(() => {        let base64 = new util.Base64Helper();        let result = base64.decodeSync(str);        return cipher.doFinal({          data: result        })      })      .then(output => {        let result = uint8ArrayToString(output.data)        return new Promise((resolve) => {          resolve(result)        })      }).catch(e => {        return new Promise((_, reject) => {          reject(e)        })      })  }).catch(e => {    return new Promise((_, reject) => {      reject(e)    })  })}/* *解密内容转换成字符串 */function uint8ArrayToString(array) {  let arrayString = '';  for (let i = 0; i  

3、网络请求

export async function httpRequestGet(url: string, formDataStrOrJson: object): Promise {  let httpRequest = http.createHttp();  let encryStr: string = await requestEncrypt(formDataStrOrJson)  let responseResult = httpRequest.request(url, {    method: http.RequestMethod.GET,    readTimeout: CommonConstant.HTTP_READ_TIMEOUT,    header: {      'Content-Type': ContentType.JSON    },    extraData: {      "data": encryStr    },    connectTimeout: CommonConstant.HTTP_READ_TIMEOUT,  });  let serverData: ResponseResultModel = new ResponseResultModel();  return responseResult.then(async (value: http.HttpResponse) => {    if (value.responseCode === CommonConstant.HTTP_CODE_200) {      let result = `${value.result}`;      let resultJson: ResponseResultModel = JSON.parse(result);      serverData.data = await decrypt(resultJson.data)      serverData.status = resultJson.status;      serverData.message = resultJson.message;    } else {      serverData.message = `${$r('app.string.http_error_message')}&${value.responseCode}`;    }    return serverData;  }).catch(() => {    serverData.message = $r('app.string.http_error_message');    return serverData;  })}///根据后端返回的参数自己替换返回参数export class ResponseResultModel {  /**   * Code returned by the network request: success, fail.   */  status: number;  /**   * Message returned by the network request.   */  message: string | Resource;  /**   * Data returned by the network request.   */  data: string | Object | ArrayBuffer;  constructor() {    this.status = 0;    this.message = '';    this.data = '';  }}

4、完整代码

/** * 请求加密 * @param json 参数 * @param key 秘钥 * @returns {string} 密文 * cipherAlgName 参考https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/cryptoframework-overview-0000001544583933-V2#ZH-CN_TOPIC_0000001573928893__%E5%8A%A0%E8%A7%A3%E5%AF%86%E8%A7%84%E6%A0%BC */function requestEncrypt(json, key = AppConstant.SECRET) {  let cipherAlgName = 'AES256|CBC|PKCS7';  //创建秘钥生成器  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256')    let ivParam: cryptoFramework.IvParamsSpec = {    algName: 'IvParamsSpec',    iv: {      //如果项目需要就将空字符替换      data: stringToUint8Array('', 32)    }  }  let cipher;  //convertKey方法是通过秘钥生成symKey  return symKeyGenerator.convertKey({    data: stringToUint8Array(key)  }).then(symKey => {    try {      //创建cipher      cipher = cryptoFramework.createCipher(cipherAlgName);      console.info(`xx cipher algName: ${cipher.algName}`);    } catch (error) {      console.error(`xx createCipher failed, ${error.code}, ${error.message}`);      return null    }    //创建cipher之后才能初始化    return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ivParam)      .then(() => {        //创建cipher且初始化之后才能执行doFinal        return cipher.doFinal({          data: stringToUint8Array(JSON.stringify(json))        })      })      .then(output => {        let base64 = new util.Base64Helper();        let result = base64.encodeToStringSync(output.data);        return new Promise((resolve) => {          resolve(result)        })      }).catch(e => {        return new Promise((_, reject) => {          reject(e)        })      })  }).catch(e => {    return new Promise((_, reject) => {      reject(e)    })  })}
export class ResponseResultModel {  /**   * Code returned by the network request: success, fail.   */  status: number;  /**   * Message returned by the network request.   */  message: string | Resource;  /**   * Data returned by the network request.   */  data: string | Object | ArrayBuffer;  constructor() {    this.status = 0;    this.message = '';    this.data = '';  }}

上一篇:电脑直播伴侣多开教程

下一篇:web怎么看服务器ip?