Jsrsasign foreground signature, Java background verification foreground signature

Source: Internet
Author: User

RSA specifically what this is not much to say. Algorithm implementation AH application AH already a lot of. Today record this special request, front desk signature, background verification

Java background generated key pair

Pom.xml adding BC Dependencies

 <Dependency>            <groupId>Org.bouncycastle</groupId>            <Artifactid>Bcprov-jdk15on</Artifactid>            <version>1.51</version>        </Dependency>

Rsatools

 PackageCom.oscgc.securevideo.server.tool.rsa;Importjava.io.IOException;ImportJava.io.StringWriter;ImportJava.security.*;ImportJava.security.interfaces.RSAPrivateKey;ImportJava.security.interfaces.RSAPublicKey;ImportJava.security.spec.PKCS8EncodedKeySpec;ImportJava.security.spec.X509EncodedKeySpec;ImportOrg.bouncycastle.openssl.PEMWriter;ImportOrg.bouncycastle.util.io.pem.PemObject;/*** Created by Yq on 2015/6/10.*/ Public classRsakeytools { Public Static FinalString Pem_publickey = "Public KEY";  Public Static FinalString Pem_privatekey = "PRIVATE KEY"; /*** Generatersakeypair * *@paramKeySize *@return     */     Public StaticKeyPair Generatersakeypair (intkeySize) {Keypairgenerator Generator=NULL; SecureRandom Random=NewSecureRandom (); Security.addprovider (NewOrg.bouncycastle.jce.provider.BouncyCastleProvider ()); Try{Generator= Keypairgenerator.getinstance ("RSA", "BC"); }        Catch(nosuchalgorithmexception e) {e.printstacktrace (); }        Catch(nosuchproviderexception e) {e.printstacktrace ();                } generator.initialize (KeySize, Random); KeyPair KeyPair=Generator.generatekeypair (); returnKeyPair; }        /*** Converttopemkey * *@paramPublicKey *@paramPrivatekey *@return     */     Public StaticString Converttopemkey (Rsapublickey publickey, Rsaprivatekey privatekey) { if(PublicKey = =NULL&& Privatekey = =NULL) {            return NULL; } StringWriter StringWriter=NewStringWriter (); Try{pemwriter Pemwriter=NewPemwriter (StringWriter, "BC"); if(PublicKey! =NULL) {Pemwriter.writeobject (NewPemobject (Pem_publickey, publickey.getencoded ())); }            Else {
The format of the Privatekey produced here is the format of Pkcs#8 Pemwriter.writeobject (NewPemobject (Pem_privatekey, privatekey.getencoded ())); } pemwriter.flush (); } Catch(IOException e) {e.printstacktrace (); } returnstringwriter.tostring (); } Public Static byte[] Sign (String data,byte[] privatekey)throwsException {pkcs8encodedkeyspec Pkcs8encodedkeyspec=NewPkcs8encodedkeyspec (Privatekey); Keyfactory keyfactory= Keyfactory.getinstance ("RSA"); Privatekey PrivateKey2=keyfactory.generateprivate (PKCS8ENCODEDKEYSPEC); Signature Signature= Signature.getinstance ("Sha1withrsa"); Signature.initsign (PrivateKey2); Signature.update (Data.getbytes ()); returnsignature.sign (); }//Background test signature to be consistent with the foreground, so you need to convert the resultsPrivate StaticString bytes2string (byte[] bytes) {StringBuilder string=NewStringBuilder (); for(byteb:bytes) {String hexstring= Integer.tohexstring (0x00FF &b); String.append (Hexstring.length ()= = 1? "0" +hexstring:hexstring); } returnstring.tostring (); } Public Static BooleanVerify (String data,byte[] PublicKey,byte[] signatureresult) { Try{x509encodedkeyspec X509encodedkeyspec=NewX509encodedkeyspec (PublicKey); Keyfactory keyfactory= Keyfactory.getinstance ("RSA"); PublicKey PublicKey2=keyfactory.generatepublic (X509ENCODEDKEYSPEC); Signature Signature= Signature.getinstance ("Sha1withrsa"); Signature.initverify (PublicKey2); Signature.update (Data.getbytes ()); returnsignature.verify (Signatureresult); } Catch(Exception e) {e.printstacktrace (); } return false; }
The signature result of the foreground is that some negative numbers in byte are converted to positive numbers.
But the back-end verification method needs to be before the conversion Public Static byte[] Hexstringtobytearray (String data) {intK = 0; byte[] results =New byte[Data.length ()/2]; for(inti = 0; i + 1 < data.length (); i + = 2, k++) {Results[k]= (byte) (Character.digit (Data.charat (i), << 4)); RESULTS[K]+= (byte) (Character.digit (Data.charat (i + 1), 16)); } returnresults; } Public Static voidMain (string[] args) {String str= "Coder"; KeyPair k= Generatersakeypair (1024); String PublicKey= Converttopemkey ((rsapublickey) k.getpublic (),NULL); String Privatekey= Converttopemkey (NULL, (Rsaprivatekey) k.getprivate ()); System.out.println ("Publickey__\n" +PublicKey); System.out.println ("Privatekey_\n" +Privatekey); Try { byte[] Signautreresult =Sign (str, k.getprivate (). getencoded ()); String Signaturestr=bytes2string (Signautreresult); byte[] SignatureResult2 =Hexstringtobytearray (SIGNATURESTR); Booleanb =Verify (str, k.getpublic (). getencoded (), SIGNATURERESULT2) ; System.out.print ("III" +b); } Catch(Exception e) {e.printstacktrace (); } } }

The Lib used by Javascript signatures is jsrsasign contains:

    • SIGNATURE-RSA/RSAPSS/ECDSA/DSA digital Signtature class wrapper of Java JCE style
    • Messagedigest-cryptographic hash Calculation class wrapper of Java JCE style
    • Mac-message Authentication code Hash calculation class wrapper of Java JCE style
    • ASN.1 Encoder/generator
    • ASN.1 structure for Ceritificate, CRL and CSR (pkcs#10) generation
    • ASN.1 structure for CMS signeddata generation
    • ASN.1 structure for RFC 3161 TimeStamp generation
    • ASN.1 structure for RFCs 5126 cades Long term Signature generation
    • Simple ASN.1 Data Parser
    • Simple Certificate Parser/reader
    • Keyutil-loading RSA/EC/DSA private/public key from PEM formatted PKCS#1/5/8 and certificate
    • JSON Web Siguature (JWS), JSON web Token (JWT) and JSON web Key (JWK)

More detailed GitHub address: https://kjur.github.io/jsrsasign/

The signature example code given on the official website is as follows:

function dosign () {  varnew  Rsakey ();  Rsa.readprivatekeyfrompemstring (document.form1.prvkey1.value);   var hashalg = document.form1.hashalg.value;   var hsig = rsa.signstring (document.form1.msgsigned.value, hashalg);   = Linebrk (hsig, +);}

Here we need to change:

Rsa.readprivatekeyfrompemstring (Document.form1.prvkey1.value);

This method is described in the official API:
readprivatekeyfrompemstring(KEYPEM) Read pkcs#1 private key from a string

This method incoming Privatekey is required pkcs#1 format, but the background generated by the private key is pkcs#8 format, here can not use this method, signature pass.

View Jsrsasign's API

Keyutil-loading RSA/EC/DSA private/public key from PEM formatted PKCS#1/5/8 and certificate

So JS generates Rsakey objects

Rsa=keyutil.getkey (Document.form1.prvkey1.value);

This method supports pkcs#8 PEM format for Privatekey that can be signed.

Jsrsasign foreground signature, Java background verification foreground signature

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.