Php,c# and Javarsa signature and verification

Source: Internet
Author: User

Php,c# and Javarsa signature and verification

This feature searches a lot of information on the Internet. Contribution, reprint must indicate and to Zhuo second sister's selfless dedication to express gratitude.

1) The signature algorithm uses SHA1WITHRSA.

2) The signed data BITS Base64 encoded ciphertext string.

3) The format of the private key for signing in three environments is different and requires the OpenSSL tool to be converted.

――――――――――――――――――――――――――――――――――――――――――

Java Signature:

1) Obtain the. Key private key from the PFX certificate that contains the public private key:

F:\openssl-0.9.8k_win32\bin>openssl pkcs12-in f:\certs\zhuo.pfx-out f:\certs\zhuo.pemEnter Import Password: (Enter the password for export) MAC verified Okenter Pem Pass phrase: (PEM certificate Password at least 4 bits long) Verifying-enter PEM Pass phrase: (Confirm once PEM certificate password) F:\openss L-0.9.8k_win32\bin>openssl pkcs8-topk8-inform pem-outform der-in f:\certs\zhuo.pem-out F:\certs\zhuo_der.key-noc Ryptenter Pass phrase for F:\certs\zhuo.pem: (Enter the PEM certificate password)
??

This step generates a . Key the file is JAVA the private key file required for signing.

2) Generate the public key: The public key certificate is exported directly from IE with the suffix of the CER in the binary encoded format.

?

?

3) Signature Verification:

?

Signature:/** * * Function Function Description: Signature data * Created by zhuoyueping 2013-8-17 * Modified by zhuoyueping 2013-8-17 * Revised content Description: * @param @pa Ram content: Original signature * @param @param keyfile: Private key file. Key path * @param @return * @param @throws Exception * @return String:bas E64 Signature * @throws */public string sign (string content, String keyfile) throws Exception {File File = new file (keyfile);//ke Yfile key file address FileInputStream in;in = new FileInputStream (file); Bytearrayoutputstream bout = new Bytearrayoutputstream (); byte[] Tmpbuf = new Byte[1024];int count = 0;while ((count = IN.R EAD (TMPBUF))! =-1) {bout.write (tmpbuf, 0, count); tmpbuf = new byte[1024];} In.close (); Keyfactory keyfactory = keyfactory.getinstance ("RSA"); Encodedkeyspec Privatekeyspec = new Pkcs8encodedkeyspec (Bout.tobytearray ()); Rsaprivatekey Privatekey = (rsaprivatekey) keyfactory.generateprivate (PRIVATEKEYSPEC); Signature DSA = signature.getinstance ("Sha1withrsa"); Using SHA1WITHRSA encryption Dsa.initsign (Privatekey);d sa.update (content.getbytes ("UTF-8")); Voucher needThe encrypted string must become a byte type byte[] sig = Dsa.sign (); String rtnvalue = new String (Base64.encode (SIG)); return rtnvalue;}  /** *

* Verify Signature *

* * @param data Original text section * @param sign signature [BASE64] * @param certificatepath certificate store Path * @return * @throws Exception */public STA Tic Boolean verifysign (byte[] data, String sign,string Certificatepath) throws Exception {//Get certificate X509Certificate X509cert Ificate = (x509certificate) getcertificate (Certificatepath); return verifysign (data,sign,x509certificate);} private static Boolean verifysign (byte[] data, String sign, X509Certificate x509certificate) throws Exception {PublicKey P Ublickey = X509certificate.getpublickey (); Signature Signature = signature.getinstance (X509certificate.getsigalgname ()); signature.initverify (PublicKey); Signature.update (data); return Signature.verify (Base64.decode (Sign.getbytes ()));}

?

C # Signature:

1) Obtain the. Key private key from the PFX certificate that contains the public private key:

f:\openssl-0.9.8k_win32\bin> OpenSSL rsa-in d:\\certs\\zhuo.pfx-nocerts-nodes-out d:\\certs\\ Zhuo.key the. Key file that is generated by this step is the private key file required for C # signing.
?

2) Public key generation: Same as Java, X509 Certificate in binary format 3) Signature and verification:

Using system;using system.text;using system.security.cryptography;using system.web;using System.IO;using  System.Security.Cryptography.X509Certificates; Namespace safe{public class Safeutil {///// Verify signature //////Original: UTF8 Code///Signature: Base64 Encoded bytes///Public Key Path///
 
  
   Verification Results
  
 public bool Verify (string originalstring, String signaturestring,string publickeypath) {//Will base64 the number of signatures                According to the transcoding byte byte[] signedBase64 = convert.frombase64string (signaturestring);                 byte[] Orgin = Encoding.UTF8.GetBytes (originalstring);                X509Certificate2 x509_cer1 = new X509Certificate2 (Publickeypath);                RSACryptoServiceProvider ORSA = new RSACryptoServiceProvider ();                Orsa.fromxmlstring (X509_Cer1.PublicKey.Key.ToXmlString (false));                BOOL bverify = Orsa.verifydata (Orgin, "SHA1", signedBase64);        return bverify; }        ////// Verify signature //////Original: UTF8 Code///Certificate path: D:/certs/mycert.key///
 
  
   Verification
  
         public string sign (string data, String privatekeypath) {RSACryptoServiceProvider RSACSP = LOADC            Ertificatefile (Privatekeypath);            byte[] Databytes = Encoding.UTF8.GetBytes (data);            byte[] signaturebytes = Rsacsp.signdata (databytes, "SHA1");        Return convert.tobase64string (signaturebytes);            } private byte[] Getpem (String type, byte[] data) {string PEM = Encoding.UTF8.GetString (data);            String header = String.Format ("-----BEGIN {0}-----", type);            String footer = String.Format ("-----END {0}-----", type); int start = Pem. IndexOf (header) + header.            Length; int end = PEM.             IndexOf (footer, start); String base64 = Pem.               Substring (Start, (End-start));        Return convert.frombase64string (base64); } Private RSACryptoServiceProvider Loadcertificatefile (string filename) {using (System.IO.FileS Tream fs = System.IO.File.OpenRead (filename) {byte[] data = new BYTE[FS.                Length];                byte[] res = NULL; Fs. Read (data, 0, data.                Length);                if (data[0]! = 0x30) {res = GETPEM ("RSA PRIVATE KEY", data);                    } try {RSACryptoServiceProvider RSA = Decodersaprivatekey (res);                return RSA;            } catch (Exception ex) {} return null; }} private RSACryptoServiceProvider Decodersaprivatekey (byte[] privkey) {byte[] modulus                         , E, D, P, Q, DP, DQ, IQ; ---------Set up stream to decode the ASN.1 encoded RSA private key------MemoryStream mem = new Memoryst            Ream (Privkey);  BinaryReader Binr = new BinaryReader (MEM); Wrap Memory Stream with BinaryReader for easy reading byte BT = 0;            UShort twobytes = 0;            int elems = 0; try {twobytes = Binr.                ReadUInt16 ();                      if (twobytes = = 0x8130)//data read as little endian order (actual data order for Sequence is 30 81) Binr.    ReadByte (); Advance 1 byte else if (twobytes = = 0x8230) binr.    ReadInt16 ();                Advance 2 bytes else return null; Twobytes = Binr.                ReadUInt16 ();                if (twobytes! = 0x0102)//version number return null; BT = Binr.                ReadByte ();                if (BT = 0x00) return null;                ------All private key components is Integer sequences----Elems = Getintegersize (BINR); modulus = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); E = Binr.                Readbytes (Elems); Elems = getintegersize (biNR); D = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); P = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); Q = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); DP = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); DQ = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); IQ = Binr.                Readbytes (Elems); -------Create RSACryptoServiceProvider instance and initialize with public key-----CspParameters Cs                Pparameters = new CspParameters ();                Cspparameters.flags = Cspproviderflags.usemachinekeystore;                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider (1024x768, CspParameters);                RSAParameters rsaparams = new RSAParameters ();                Rsaparams.modulus = modulus;                Rsaparams.exponent = E; Rsaparams.d= D;                RSAPARAMS.P = P;                RSAPARAMS.Q = Q;                RSAPARAMS.DP = DP;                RSAPARAMS.DQ = DQ;                Rsaparams.inverseq = IQ; Rsa.                ImportParameters (Rsaparams);            return RSA;            } catch (Exception ex) {return null; } finally {Binr.            Close ();            }} private int getintegersize (BinaryReader binr) {byte BT = 0;            byte lowbyte = 0x00;            byte highbyte = 0x00;            int count = 0; BT = Binr.            ReadByte ();            if (BT! = 0x02)//expect integer return 0; BT = Binr.            ReadByte (); if (BT = = 0x81) Count = Binr.    ReadByte (); Data size in next byte else if (BT = = 0x82) {Highbyte = Binr. ReadByte (); Data size in next 2 Bytes Lowbyte = binr.                    ReadByte ();                    Byte[] Modint = {lowbyte, highbyte, 0x00, 0x00};                Count = Bitconverter.toint32 (modint, 0);     } else {count = BT; We already has the data size} while (Binr.            ReadByte () = = 0x00) {//remove High order zeros in data count-= 1; } binr.       Basestream.seek ( -1, seekorigin.current);        Last ReadByte wasn ' t a removed zero, so back up a byte return count; }      }}

?

PHP Signature:

1) Obtain the. Key private key from the PFX certificate that contains the public key: Consistent certificate in C #

2) Public key generation:

F:\openssl-0.9.8k_win32\bin>openssl pkcs12-in f:\certs\zhuo.pfx-out F:\certs\zhuo.pem

?

3) Signature and verification:

/* Signature data: Data:utf-8 encoded order original, Privatekeyfile: Private key path passphrase: Private key password return: Base64 transcoding signature Data */function sign ($data, $ Privatekeyfile, $passphrase) {   $signature = "; $privatekey = Openssl_pkey_get_private (file_get_contents ($ Privatekeyfile), $passphrase);  $res =openssl_get_privatekey ($privatekey);  Openssl_sign ($data, $signature, $res);  Openssl_free_key ($res);    Return Base64_encode ($signature);} /* Verify Signature: Data: Original signature: Signature Publickeypath: Public key path return: Signature result, true for verification success, false for check failure */function Verity ($data, $signature, $ Publickeypath) {$pubKey = file_get_contents (' D:/certs/test.pem '); $res = Openssl_get_publickey ($pubKey); $result = ( BOOL) openssl_verify ($data, Base64_decode ($signature), $res); Openssl_free_key ($res); return $result;}

* PHP needs to pay attention to the version and some of the package import, if there is an error again Google ~ ~

?

?

?

?

?

?

  • Related Article

    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.

    Tags Index: