react-native RSA 非对称加密

今天要介绍的是 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'
    }
});
 

公钥和私钥替换成自己的公钥私钥。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值