【React Native】AES+Base64加密
source link: https://anye3210.github.io/2020/08/03/【React-Native】AES加密/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在移动端App开发中, AES
加密非常常用,本文主要讲解如何在 React Native
中封装自己的 AES
加密工具类及会遇到的坑。这里的 AES
加密是基于前端常用的加密库
crypto-js
。
安装crypto-js
使用 NPM
或者 Yarn
安装 crypto-js
# NPM npm install crypto-js # Yarn yarn add crypto-js
注意:使用 crypto-js
4.0.0
及以上的版本会报找不到Crypto.js的错,这可能是新版本的Bug,需要在 package.json
中找到 crypto-js
并把版本号指定为 ^3.3.0
(与3.3.0版本兼容,相当于3.X.X, 即>=3.3.0 < 4.0.0,不改变大版本号),然后重新执行 npm install
:
"crypto-js": "^3.3.0", //
创建加密工具类
新建 AESTool.js
文件,添加如下代码:
import CryptoJS from 'crypto-js' const key = CryptoJS.enc.Utf8.parse('abcdef0123456789'); const iv = CryptoJS.enc.Utf8.parse("0123456789abcdef"); export const AESTool = { encrypt: (message) => { let sendData = CryptoJS.enc.Utf8.parse(message); let encrypted =CryptoJS.AES.encrypt(sendData,key,{ iv: iv, mode:CryptoJS.mode.CBC, padding:CryptoJS.pad.Pkcs7 }); return encrypted.toString(); //Base64字符串 }, decrypt: (message) => { let decrypt = CryptoJS.AES.decrypt(message, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return decrypt.toString(CryptoJS.enc.Utf8); } }
这里使用的是 CBC
加密模式,使用了 Pkcs7
补码方式。需要注意的是加密方法里传的明文、偏移量、密钥等参数都需要使用 CryptoJS.enc.Utf8.parse()
方法解析之后使用。
注意:这里 CryptoJS
加密后的字符串就是 Base64
编码的,不需要重复进行Base64编码。解密的时候也直接传 Base64
字符串即可。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK