当前位置:   article > 正文

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

arkts base64 aes加密

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

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

正文开始 直接上代码

1、参数加密

  1. /**
  2. * 请求加密
  3. * @param json 参数
  4. * @param key 秘钥
  5. * @returns {string} 密文
  6. * 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
  7. */
  8. function requestEncrypt(json, key = AppConstant.SECRET) {
  9. let cipherAlgName = 'AES256|CBC|PKCS7';
  10. //创建秘钥生成器
  11. let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256')
  12. let ivParam: cryptoFramework.IvParamsSpec = {
  13. algName: 'IvParamsSpec',
  14. iv: {
  15. //如果项目需要就将空字符替换
  16. data: stringToUint8Array('', 32)
  17. }
  18. }
  19. let cipher;
  20. //convertKey方法是通过秘钥生成symKey
  21. return symKeyGenerator.convertKey({
  22. data: stringToUint8Array(key)
  23. }).then(symKey => {
  24. try {
  25. //创建cipher
  26. cipher = cryptoFramework.createCipher(cipherAlgName);
  27. console.info(`xx cipher algName: ${cipher.algName}`);
  28. } catch (error) {
  29. console.error(`xx createCipher failed, ${error.code}, ${error.message}`);
  30. return null
  31. }
  32. //创建cipher之后才能初始化
  33. return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ivParam)
  34. .then(() => {
  35. //创建cipher且初始化之后才能执行doFinal
  36. return cipher.doFinal({
  37. data: stringToUint8Array(JSON.stringify(json))
  38. })
  39. })
  40. .then(output => {
  41. let base64 = new util.Base64Helper();
  42. let result = base64.encodeToStringSync(output.data);
  43. return new Promise((resolve) => {
  44. resolve(result)
  45. })
  46. }).catch(e => {
  47. return new Promise((_, reject) => {
  48. reject(e)
  49. })
  50. })
  51. }).catch(e => {
  52. return new Promise((_, reject) => {
  53. reject(e)
  54. })
  55. })
  56. }
  57. /**
  58. *把密钥、明文等转换成输入数据需要的格式
  59. */
  60. function stringToUint8Array(str, len = null) {
  61. let arr = [];
  62. if (len == null) {
  63. len = str.length
  64. }
  65. for (let i = 0; i < len; i++) {
  66. if (str.length > i) {
  67. arr.push(str.charCodeAt(i))
  68. } else {
  69. arr.push(0)
  70. }
  71. }
  72. return new Uint8Array(arr);
  73. }

2、参数解密

  1. /**
  2. * 解密
  3. * @param str 密文
  4. * @param key 私钥
  5. * @returns {*|string} 明文
  6. */
  7. function decrypt(str, key = AppConstant.SECRET) {
  8. let cipherAlgName = 'AES256|CBC|PKCS7';
  9. let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256')
  10. let ivParam: cryptoFramework.IvParamsSpec = {
  11. algName: 'IvParamsSpec',
  12. iv: {
  13. data: stringToUint8Array('', 32)
  14. }
  15. }
  16. let cipher;
  17. return symKeyGenerator.convertKey({
  18. data: stringToUint8Array(key)
  19. }).then(symKey => {
  20. try {
  21. cipher = cryptoFramework.createCipher(cipherAlgName);
  22. console.info(`xx cipher algName: ${cipher.algName}`);
  23. } catch (error) {
  24. console.error(`xx createCipher failed, ${error.code}, ${error.message}`);
  25. return null
  26. }
  27. return cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, ivParam)
  28. .then(() => {
  29. let base64 = new util.Base64Helper();
  30. let result = base64.decodeSync(str);
  31. return cipher.doFinal({
  32. data: result
  33. })
  34. })
  35. .then(output => {
  36. let result = uint8ArrayToString(output.data)
  37. return new Promise((resolve) => {
  38. resolve(result)
  39. })
  40. }).catch(e => {
  41. return new Promise((_, reject) => {
  42. reject(e)
  43. })
  44. })
  45. }).catch(e => {
  46. return new Promise((_, reject) => {
  47. reject(e)
  48. })
  49. })
  50. }
  51. /*
  52. *解密内容转换成字符串
  53. */
  54. function uint8ArrayToString(array) {
  55. let arrayString = '';
  56. for (let i = 0; i < array.length; i++) {
  57. arrayString += String.fromCharCode(array[i]);
  58. }
  59. return arrayString;
  60. }

3、网络请求

  1. export async function httpRequestGet(url: string, formDataStrOrJson: object): Promise<ResponseResultModel> {
  2. let httpRequest = http.createHttp();
  3. let encryStr: string = await requestEncrypt(formDataStrOrJson)
  4. let responseResult = httpRequest.request(url, {
  5. method: http.RequestMethod.GET,
  6. readTimeout: CommonConstant.HTTP_READ_TIMEOUT,
  7. header: {
  8. 'Content-Type': ContentType.JSON
  9. },
  10. extraData: {
  11. "data": encryStr
  12. },
  13. connectTimeout: CommonConstant.HTTP_READ_TIMEOUT,
  14. });
  15. let serverData: ResponseResultModel = new ResponseResultModel();
  16. return responseResult.then(async (value: http.HttpResponse) => {
  17. if (value.responseCode === CommonConstant.HTTP_CODE_200) {
  18. let result = `${value.result}`;
  19. let resultJson: ResponseResultModel = JSON.parse(result);
  20. serverData.data = await decrypt(resultJson.data)
  21. serverData.status = resultJson.status;
  22. serverData.message = resultJson.message;
  23. } else {
  24. serverData.message = `${$r('app.string.http_error_message')}&${value.responseCode}`;
  25. }
  26. return serverData;
  27. }).catch(() => {
  28. serverData.message = $r('app.string.http_error_message');
  29. return serverData;
  30. })
  31. }
  32. ///根据后端返回的参数自己替换返回参数
  33. export class ResponseResultModel {
  34. /**
  35. * Code returned by the network request: success, fail.
  36. */
  37. status: number;
  38. /**
  39. * Message returned by the network request.
  40. */
  41. message: string | Resource;
  42. /**
  43. * Data returned by the network request.
  44. */
  45. data: string | Object | ArrayBuffer;
  46. constructor() {
  47. this.status = 0;
  48. this.message = '';
  49. this.data = '';
  50. }
  51. }

4、完整代码

  1. /**
  2. * 请求加密
  3. * @param json 参数
  4. * @param key 秘钥
  5. * @returns {string} 密文
  6. * 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
  7. */
  8. function requestEncrypt(json, key = AppConstant.SECRET) {
  9. let cipherAlgName = 'AES256|CBC|PKCS7';
  10. //创建秘钥生成器
  11. let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256')
  12. let ivParam: cryptoFramework.IvParamsSpec = {
  13. algName: 'IvParamsSpec',
  14. iv: {
  15. //如果项目需要就将空字符替换
  16. data: stringToUint8Array('', 32)
  17. }
  18. }
  19. let cipher;
  20. //convertKey方法是通过秘钥生成symKey
  21. return symKeyGenerator.convertKey({
  22. data: stringToUint8Array(key)
  23. }).then(symKey => {
  24. try {
  25. //创建cipher
  26. cipher = cryptoFramework.createCipher(cipherAlgName);
  27. console.info(`xx cipher algName: ${cipher.algName}`);
  28. } catch (error) {
  29. console.error(`xx createCipher failed, ${error.code}, ${error.message}`);
  30. return null
  31. }
  32. //创建cipher之后才能初始化
  33. return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ivParam)
  34. .then(() => {
  35. //创建cipher且初始化之后才能执行doFinal
  36. return cipher.doFinal({
  37. data: stringToUint8Array(JSON.stringify(json))
  38. })
  39. })
  40. .then(output => {
  41. let base64 = new util.Base64Helper();
  42. let result = base64.encodeToStringSync(output.data);
  43. return new Promise((resolve) => {
  44. resolve(result)
  45. })
  46. }).catch(e => {
  47. return new Promise((_, reject) => {
  48. reject(e)
  49. })
  50. })
  51. }).catch(e => {
  52. return new Promise((_, reject) => {
  53. reject(e)
  54. })
  55. })
  56. }
  1. export class ResponseResultModel {
  2. /**
  3. * Code returned by the network request: success, fail.
  4. */
  5. status: number;
  6. /**
  7. * Message returned by the network request.
  8. */
  9. message: string | Resource;
  10. /**
  11. * Data returned by the network request.
  12. */
  13. data: string | Object | ArrayBuffer;
  14. constructor() {
  15. this.status = 0;
  16. this.message = '';
  17. this.data = '';
  18. }
  19. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/294087
推荐阅读
相关标签
  

闽ICP备14008679号