今天要介绍的是 RSA非对称加密。 非对称加密分为两个秘钥,公钥和私钥。
关于rsa加密过长的一种解决方案是,先采用MD5加密明文,再对加密后的md5 进行rsa加密。
1.先用openssl生成 公钥和私钥,不会的自己百度。
2. 下面是rn的 rsa 加密步骤:
先添加依赖库:
npm i jsencrypt
然后 加解密代码如下:
import React, {Component} from 'react';
import {
Button,
StyleSheet, Text, TextInput,
View
} from 'react-native';
import 'jsencrypt';
// 公钥
const PUB_KEY = 'xxx';
// 私钥
const PRIV_KEY = 'xxx';
export default class Demo extends Component{
constructor(props) {
super(props);
this.state = {
data: '',
text: ''
}
}
render(){
return (
<View style={styles.container}>
<TextInput
onChangeText={(text) => this.setState({data: text})}
/>
<Button
title='加密'
onPress={() => this.encrypt()}
/>
<Button
title='解密'
onPress={() => this.decrypt()}
/>
<Text>{this.state.text}</Text>
</View>
)
}
/**
* 加密
*/
encrypt() {
let encrypt = new JSEncrypt();
encrypt.setPublicKey(PUB_KEY);
let encrypted = encrypt.encrypt(this.state.data);
console.log('encrypt------->'+encrypted);
this.setState({
text: encrypted
})
}
/**
* 解密
*/
decrypt() {
let decrypt = new JSEncrypt();
decrypt.setPrivateKey(PRIV_KEY);
let decrypted = decrypt.decrypt(this.state.text);
this.setState({
text: decrypted
})
}
}
/**
* 样式属性
*/
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#DDD'
}
});
公钥和私钥替换成自己的公钥私钥。