openssl+ front-end Jsrsa signature + back-end Nodejs verification

Source: Internet
Author: User
Tags base64 install openssl sha1 asymmetric encryption

As the title shows, the overall section is divided into three parts:

First, install OpenSSL under WIN10 and then generate the RSA public and private key via the OpenSSL tool

(1) Win10 under the installation of OpenSSL required tools are: Vs2013,perl,nasm,openssl source

Among them, VS2013 installation, registration and activation please self-Baidu, ActivePerl, NASM and OpenSSL source code also please download the installation yourself, ActivePerl say (Execute Perl example.pl, if prompted: Hello from activeperl! The Perl installation is successful), NASM I chose the nasm-2.11.02-installer.exe,openssl part of the version in the later configuration will be error, I chose the last Openssl-1.0.2j.tar.gz (SHA256) ( PGP sign) (SHA1).

(2) Setting environment variables

Open My Computer, properties, advanced system settings, environment variables, locate the path system variable, click Edit, add C:\Program Files (x86) \microsoft Visual Studio 12.0\vc\bin; C:/perl64/bin; C:/nasm;c:/windows/system32

I am the default instructions are all placed in the C drive, you can modify the installation path according to circumstances, it will be installed in the path of the C:/perl64/site/bin, there is a dmake.exe run file, where I copy it to their own manually added C:/perl64 In addition to the/bin directory, copy the Name.exe and Ndisasm.exe below C:/nasm to C:\Program Files (x86) \microsoft Visual Studio 12.0\vc\bin, After setting the environment variables, remember to restart your computer to take effect.

(3) Execution of orders

Open the developer command prompt for Visual studio (for a half day, originally placed in C:\Program Files (x86) \microsoft Visual Studio 12.0\common7\tools\shortcuts), and enter the directory of OpenSSL (I put in the C packing directory), execute the command perl Configure vc-win32--prefix=c:/openssl Note: Here the prefix is used to specify the installation directory. Then run ms\do_nasm to create the makefile file, run Nmake-f Ms\ntdll.mak to build the OpenSSL dynamic library (if the error cannot open include file: ' Windows.h ', You need to navigate to C:\Program Files (x86) \microsoft Visual Studio 12.0\vc\bin run Vcvars32.bat to set the VC command-line compilation environment variable), and then wait patiently ... Then run Nmake-f Ms/ntdll.mak test, and if passed all tests is displayed, you can run nmake-f Ms\ntdll.mak install to mount the compiled OpenSSL to the previously specified directory. To view the installation results, there are three folders bin, Lib, and include under C:\openssl, where the bin directory includes openssl.exe (OpenSSL instruction program), Ssleay32.dll (SSL protocol dynamic Library), Libeay32.dll (cipher algorithm library), the Lib directory includes the Ssleay32.lib,libeay32.lib,include directory includes the OpenSSL development design of the header file. In addition, if you have previously compiled an error, please first clear: nmake-f Ms\ntdll.mak clean.

(4) Generating the public and private keys of RSA

Open the Bin folder under Openssl.exe, run Genrsa-out RSA_PRIVATE_KEY.PEM 1024 to generate a PEM format file named Rsa_private_key in the current directory, open it in Notepad, You can see-----begin with the RSA private key-----,-----End of the RSA private key-----No newline string, this is the original private key;

Then run Pkcs8-topk8-inform pem-in rsa_private_key.pem-outform pem–nocrypt-out Pkcs8_rsa_private_key.pem convert the private key to PKCS8 lattice , the converted results can be seen on the command line, or in a PEM format file named Pkcs8_rsa_private_key that is generated under the current directory;

Finally run rsa-in rsa_private_key.pem-pubout-out RSA_PUBLIC_KEY.PEM generate the public key, which can be seen in a PEM format file named Rsa_public_key generated under the current directory, Note that this is based on the original private key before the conversion.

Second, front-end Jsrsa signature

Text look tired, or directly on the code bar ...

//introduction of Asymmetric encryption RSA's foreground signature file (on GitHub, I'm under version 6.2.2)Import jsrsasign from "Jsrsasign";//There are many useful objects in the imported Jsrsasign module, which correspond to different methods.Console.log (jsrsasign)//the introduction of the private key file (the general Java background generated key pair of the private key is placed in the Pem file, you can put inside the contents (string format, with the head and tail, newline with \) out to put into the JS file, and then exported with Module.exports)Import Privatekey from "Privatekey.js";//Instantiate RSAvarRsa=NewJsrsasign.rsakey ();//Incoming private key//The default incoming private key is in pkcs#1 format, so the readprivatekeyfrompemstring (Keypem) method is used//rsa.readprivatekeyfrompemstring (privatekey);//if the private key produced in the background is in pkcs#8 format, you cannot use the readprivatekeyfrompemstring (KEYPEM) methodRsa=Jsrsasign.KEYUTIL.getKey (key);//sorts the JSON data to be signed, stitching it into the parameter form of the URL to be concatenated with = and &, followed by the JSON object to be sorted, in reverse order (default = False)functionJsonurlparams (json,reverse) {//create an empty array    varJsonarr = []; //import JSON objects into an empty array     for(varIinchJSON) {        varobj ={} Obj[i]=Json[i];    Jsonarr.push (obj); }    //array length less than 2 or not JSON formatted data    if(Jsonarr.length < 2 | |typeofJsonarr[0]!== "Object")returnJsonarr; //Sort by Number type    if(typeofGetKey (jsonarr[0]) = = = "Number") {Jsonarr.sort (function(x, Y) {returnGetKey (x)-GetKey (y)}); }    //Sort String Types    if(typeofGetKey (jsonarr[0]) = = = "string") {        //Sort by character-coded orderJsonarr.sort (function(x, Y) {returnGetKey (x). charCodeAt ()-GetKey (y). charCodeAt ()}); }            //Reverse    if(reverse) {jsonarr.reverse (); }            //Create an empty string    varjsonstring = "";  for(varIinchJsonarr) {        if(I < Jsonarr.length-1) {jsonstring+ = GetKey (Jsonarr[i]) + "=" + Jsonarr[i][getkey (Jsonarr[i]) + "&"                                    }Else{jsonstring+ = GetKey (Jsonarr[i]) + "=" +Jsonarr[i][getkey (Jsonarr[i])}} //encapsulation function Gets the JSON key    functionGetKey (JSON) { for(varIinchJSON) {            returni; }    }                returnjsonstring;} varSignparams =jsonurlparams (data)//Choose which hash algorithm (hash generates a message digest for tamper-proof purposes)varHashalg= "SHA1";//signature (The private key is encrypted for the generated digest for authentication purposes)varsign=rsa.signstring (SIGNPARAMS,HASHALG);//turn signature results into Base64 encoded formatsign=jsrsasign.hex2b64 (sign);//In General, the signed parameters are placed at the end of the JSON data that needs to be passed, and the corresponding field name is Signturedata["signature"]=sign;

Third, back-end Nodejs signature (using the Express framework 4.14.0)

(1) The first simple encapsulation of two functions, remember to introduce JavaScript encryption library Crypto.js:

//encapsulates a function that converts a public key line string into a PEM-encoded format stringfunctionKeypem (str, INSERT_STR, SN) {varNewstr = "";  for(vari = 0; i < str.length; i + =sn) {        varTMP = str.substring (i, i +SN); Newstr+ = tmp +Insert_str; }    returnnewstr;}//Package verification function, data is the front end of the JSON data, sign is the front-end generated signature string, key is the public key of the verificationfunctionverifysign (data,sign,key) {//Note that if the JSON data is passed in with a signature key value pair, you need to first remove it    Deletedata["Signature"]; //If the upload data is sorted and string-stitched before the front-end signature, the same operation is done here, that is, to maintain the same source data for the signature and verification, continue to invoke the previously encapsulated Jsonurlparams function    vardata =jsonurlparams (data); //If sign takes a string between the ends of the public key file, you need to first stitch it back into the original PEM encoding format    //var key = Keypem (key, "\ n", +);    //key = '-----BEGIN public key-----\ n ' + key + '-----END public key-----';Console.log ("Data that needs to be verified for signature:" +data); Console.log ("The public key for verifying the signature: \ n" +key); //Select the hash algorithm that matches the front-end signature    varverifier = crypto.createverify (' rsa-sha1 ')); //prevent Chinese garbled charactersVerifier.update (NewBuffer (data, ' utf-8 '))); //Output verification results, if the front end is signed using Base64 encoding, here also to do the same    returnVerifier.verify (key, sign, ' base64 '); }

(2) Call the above function where verification is required

    //get upload JSON data    vardata =Req.body; //get the signature string in the upload JSON data    varSign = data["signature"]; //gets the public key of the PEM-encoded format generated by OpenSSL    varKey = "-----BEGIN public KEY-----\ n" + "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdah6/6+yvya2fmf6h8ubmivr20\n" + "zbardld j1xg12w52xc47xthrvp+prufounug58onro1syd3viz6ezuclfvc/e8ss\n "+" 6y6/4wdyasnke1twh+ m52o7s5icfiulm6flulc9rxxbzz6at1ptd/jdrukbtagtx\n "+" c+sr6oyh2uaqlra3qqidaqab\n "+"-----END public KEY-----"; //var key = "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdah6/6+yvya2fmf6h8ubmivr20zbardldj1xg12w52xc47xthrvp+ prufounug58onro1syd3viz6ezuclfvc/e8ss6y6/4wdyasnke1twh+m52o7s5icfiulm6flulc9rxxbzz6at1ptd/jdrukbtagtxc+ Sr6oyh2uaqlra3qqidaqab ";    //passing three parameters into encapsulated check function    varresult = Verifysign (Data,sign,key);

openssl+ front-end Jsrsa signature + back-end Nodejs verification

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.