React Native + Nodejs login with RSA encryption

Source: Internet
Author: User
Tags base64 decrypt asymmetric encryption

want to use RN to make a RSA (Asymmetric encryption) Login

The basic process is to generate RSA on the server side, the "public key" to the client, and then the client with "public key" encryption information sent to the server, the service end with the private key decryption.

The process is not complicated, the problem is that Nodejs and RN are prepared to use JS to do RSA encryption, originally wanted to do with Node-rsa, but do not understand how it set public key encryption

So directly to do Node-rsa base library http://www-cs-students.stanford.edu/~tjw/jsbn/, simple encapsulation of the next to do a demo

Client:

' Use strict '; Const React= Require (' react-native ');varUrl= "192.168.1.103:8082"varrsaclient= require ('./rsa-client ');//Client RSA Encryptionvar_publickey =Newrsaclient ();//Initialize "Public key"Fetch (' HTTP//' +url+ '/rsa '). Then ((response)=Response.json ()). Then (ret)={_publickey.setpublic (RET.N, RET.E); }). Done ();//"Public key" encryption, the encrypted data is hex encoded longer, so turn into Base64varencrypt=function(val) {varhex2b64 = require ('./base64 ')). hex2b64; returnhex2b64 (_publickey.encrypt (Val));};varlogin=function(data,dosuccess,doerror) {Fetch (' HTTP//' +url+ '/login ', {method:' POST ', headers: {' Accept ': ' Application/json ',            ' Content-type ': ' Application/json ',}, Body:JSON.stringify (data)}). Then (function(response) {returnResponse.json ();}) . Then (function(resdata) {dosuccess (resdata); }). Done ();};var{View, Text, TextInput, StyleSheet, touchableopacity}=React;varIndex =React.createclass ({getinitialstate:function() {    return{userName:"", PassWord:"", Encrypted:""    }; }, Render:function() {    return (      <view style={{bordercolor: ' #FA6778 ', Justifycontent:' Center ', Flex:1,                    }}> <view style={{flex:1}}> <text>encrypted = { This.state.encrypted}</text> <text>decrypted = { This.state.decrypted}</text> </View> <view style={{flex:1.2}}> <view Style={styles.singleline}> <textinput autocapitalize= "None"style={{flex:1, Fontsize:16,padding:6,borderwidth:0,textdecorationline: ' None '}} Placeholder= "User Name"Onchangetext={(text) =              {  This. SetState ({username:text});}} Value={ This. State.username}/> </View> <view style={styles.singleline}> <textinput placeholder= "Passwor DPassword={true} style={{flex:1, Fontsize:16,padding:6,borderwidth:0,textdecorationline: ' None '}} onchangetext={(text) =              {  This. SetState ({password:text});}} Value={ This. State.password}/> </View> <touchableopacity style={styles.btn} onpress={                          ()={Let _pwd= Encrypt ( This. State.password); Login ({userName: This. State.username,password:_pwd}, (Retjson)= {            if(1==retjson.loginstate) {                         This. SetState ({encrypted:retjson.encrypted,decrypted:retjson.decrypted});          }          }); }          }> <text style={{flex:1, FontSize:18, Alignself:' Center ',          }}>OK</Text> </TouchableOpacity> </View> <view style={{flex:1}}></view&gt         ; </View>);  }});varStyles =stylesheet.create ({btn: {alignself:' Stretch ', Alignitems:' Center ', Justifycontent:' Center ', BackgroundColor:' #3333FF ', Height:40, Borderradius:5, margin:8, padding:8,},singleline: {height:40, BorderWidth:1, Borderradius:5, BorderColor:' LightBlue ', margin:15,},}); Module.exports=index;

Service side:

varrouter= require (' Router ')), HTTP= Require (' http '), FS= Require (' FS '), Path= Require (' path ');/*Module.idmodule.filenamemodule.loadedmodule.parentmodule.childrenconsole.log (module);*/varRouter =Router ()//**************rsa begin************************varRsaservice = require ('./rsaservice '));var_key =NewRsaservice.rsakey (); _key.generate (384, "10001");/*Console.log ("Generating RSA Key ..."), Console.log ("_key e"); Console.log (_key.e.tostring); Console.log ("_key n "); Console.log (_key.n.tostring); Console.log (" _key d "); Console.log (_key.d.tostring (+)); Console.log (" _key p " ); Console.log (_key.p.tostring); Console.log ("_key Q"); Console.log (_key.q.tostring (+)); Console.log ("_key DMP1 "); Console.log (_key.dmp1.tostring); Console.log (" _key dmq1 "); Console.log (_key.dmq1.tostring); console.log ("_key Coeff"); Console.log (_key.coeff.tostring ());*/varhex2b64 =rsaservice.hex2b64;varb64tohex=Rsaservice.b64tohex;varPublickey={e:_key.e.tostring (+), n:_key.n.tostring (16)};//Public KeyRouter.get ('/rsa ', function(req, res) {Res.setheader (' Content-type ', ' Application/json; Charset=utf-8 ') Res.write (json.stringify (PublicKey)); Res.end ();}); Router.post ('/login ',function(req, res) {var_cnt=0; varBODY = ' '; Req.on (' Data ',       function(data) {body+=data; _cnt++; //Too much POST data, kill the connection!        //1e6 = = = 1 * MATH.POW (6) = = = 1 * 1000000 ~ ~ ~ 1MB        if(Body.length > 1e6) Request.connection.destroy ();    }); Req.on (' End ',       function () {        //var post = Qs.parse (body);        //Use post[' blah '], etc.        var_state=1,_pwd= "; var_pobj=Json.parse (body); if(_pobj.password) {Try{_pwd=_key.decrypt (B64tohex (_pobj.password));//key.decrypt (_pobj.password, ' utf8 ');Console.log (' _pwd: ', _PWD); }Catch(er) {console.log (er); _state=0; _pwd= "ERROR";            } res.write (Json.stringify ({loginstate:_state,encrypted:_pobj.password,decrypted:_pwd}));            } res.end (); Console.log (' Time= ' +Date.now ()); });});varServer =Http.createserver (function(req, res) {Console.log (Req.url); Router (req, res,function(req,res) {});}); Server.listen (8082, ':: ',    function() {Console.log (' HTTP server listening on port 8082 time= ' +Date.now ()); });

Client/Service side RSA file Http://files.cnblogs.com/files/Grart/rsa.rar

React Native + Nodejs using RSA encrypted login

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.