今天要介紹的是 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'
}
});
公鑰和私鑰替換成自己的公鑰私鑰。