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

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

本文基于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 < len; i++) {
    if (str.length > 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 < array.length; i++) {
    arrayString += String.fromCharCode(array[i]);
  }
  return arrayString;
}

3、网络请求


export async function httpRequestGet(url: string, formDataStrOrJson: object): Promise<ResponseResultModel> {
  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 = '';
  }
}

  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值