node原生有 crypto 模块,基本支持各种加密方式,奈何 React Native并不支持这些模块,可以使用以下方式破解
rn-nodeify
此类库是用 hack 方法添加 nodejs 核心模块 github
react-native-crypto
此类库支持在 React Native 中使用 node 的 crypto 模块 github
安装
npm i --save eshint
npm i --save react-native-crypto
npm i --save react-native-randombytes
react-native link react-native-randombytes
npm i --save-dev tradle/rn-nodeify
./node_modules/.bin/rn-nodeify --hack --install
#rnpm link
应用
import './shim.js';
import crypto from 'crypto';
import AESCrypt from './AESCrypt';
import RSACrypt from './RSACrypt';
...
componentDidMount(){
//AES加密
var iv = new Buffer.from("xxxxxxxxxxxxxxxx")
var key = 'xxxx'
var data = {
username: 'zhang',
pwd: '123'
}
var encryptResult = AESCrypt.encrypt(key, iv, JSON.stringify(data))
this._basicAlert('AES加密结果',encryptResult.toString(),
[
{text: '解密', onPress: () => {
var decryptResult = AESCrypt.decrypt(key, iv, encryptResult)
this._basicAlert('AES解密结果',decryptResult,[{text: '关闭'},])
}},
{text: '关闭'},
]
)
const public_key = '';
const private_key = '';
//RSA加密解密
var msg = JSON.stringify(data)
var rsaEncryptResult = RSACrypt.encrypt(public_key, msg)
this._basicAlert('RSA加密结果',rsaEncryptResult + "",
[
{text: '解密', onPress: () => {
var rsaDecryptResult = RSACrypt.decrypt(privateKey, rsaEncryptResult);
this._basicAlert('RSA解密结果',rsaDecryptResult,[{text: '关闭'},])
}},
{text: '关闭'},
]
)
}
_basicAlert = (title, msg, action) => {
Alert.alert(
title,
msg,
action,
{ cancelable: false }
)
}
}
...
Troubleshooting
由于网络原因,在执行安装过程中,部分模块可能安装不完全,在运行程序时出现“XX”模块找不到的错误,此时需再执行以下命令
npm i --save-dev tradle/rn-nodeify
./node_modules/.bin/rn-nodeify --hack --install -o
# 附:
## AESCrypt模块
import './shim.js'
import crypto from 'crypto'
var AESCrypt = {};
AESCrypt.decrypt = function(cryptkey, iv, encryptdata) {
encryptdata = new Buffer(encryptdata, 'base64').toString('binary');
var decipher = crypto.createDecipheriv('aes-128-cbc', cryptkey, iv);
var decoded = decipher.update(encryptdata, 'binary', 'utf8');
decoded += decipher.final('utf8');
return decoded;
}
AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-128-cbc', cryptkey, iv);
var encryptdata = encipher.update(cleardata, 'utf8', 'binary');
encryptdata += encipher.final('binary');
var encode_encryptdata = new Buffer(encryptdata, 'binary').toString('base64');
return encode_encryptdata;
}
module.exports = AESCrypt;
## RSACrypt模块
import './shim.js'
import crypto from 'crypto'
var RSACrypt = {};
RSACrypt.decrypt = function( privateKey, encryptdata) {
let decoded = crypto.privateDecrypt(private_key, es).toString()
return decoded;
}
RSACrypt.encrypt = function(publicKey, cleardata) {
let encode_encryptdata = crypto.publicEncrypt(public_key,new Buffer(cleardata))
return encode_encryptdata;
}
module.exports = RSACrypt;
# 参考
<https://www.jianshu.com/p/da790ff4efb0>