java/php/c# version RSA Signature and Java verification implementation

Source: Internet
Author: User
Tags begin rsa private key key string modulus openssl rsa
RSA Signature java/php/c# Version and Java verification implementation

???? in the open platform area, the SDK needs to be provided to the ISV, and signing is one of the features that need to be provided in the SDK. Because the development language used by ISVs is not single, the SDK needs to be available in multiple languages. such as Java, PHP, C #. In addition, in e-commerce, especially in the payment field, the security requirements are relatively high, so the asymmetric key RSA will be used

???? This article mainly describes how to use RSA signature on the client based on Java, PHP, C #, and then use Java verification on the server side.

?

    1. Generating RSA public private key pair based on OpenSSL
a) Download the OpenSSL tool from the web, preferably a version that is not compiled under Windows, such as:http://www.deanlee.cn/programming/openssl-for-windows/

? b) Generate private key

Go to the bin directory of OpenSSL and execute the following command:

OpenSSL genrsa-out Rsa_private_key.pem 1024

The newly generated private key file Rsa_private_key.pem will be seen in the bin directory with the following file contents:

-----BEGIN RSA PRIVATE KEY-----miicxgibaakbgqdtd1lksx6ylsaewfi7e/ Ut8krjy9pq7sgykhim9tvidziq5xzyaw8nolzkz1k486mepyg4tsuoaxsbwuplwvuzyfvnuzo7awcigkn16uwtm4nxc/+dwce+ bhckrllbtwi8l580lte7gxclth8z7ghq59ivhaogbk7fnxlufb4tsqidaqabaogbaigtk0x1j+hi8khmyppxojcopomi1s9ueewtd7fxab+ 4g5mbuv/dj62a7nadoki9iyuqe9l3ppvtolmfxcofkku0p4j7mejdz+cjvvgextkwa80nj/uzim1ool6yhwh4ztpty+pfctk1rdn3+ 070qbb9tnvntbn/jq0ld7f0t7unakea9ryi0kxjl9pupo9neewucuo4xcl9x/m9+mtkfy3vodddv1e/ eujmotfanywrjcddiqro0mlyedootilpn77qowjbapzhtv/+pqmvtrlxwnvklz4zvtppgjqqkfdhwwylz7okzb3vbqrt/ jlfxuycn2ecp7rglrxnaz7aybftf0ajhescqqddnfkequlqn0gpcddowkril1ppkhgwmwlg1ltetvjgei6kx/prl/ vgeiz1dzgctujaoy9r1cefxm/paqh3+/f/akeazstcp6q2hlbldrewkq7ocdiiwkpr5dbgy/rqr6cd7eytdxyeh5gpu1wxkjy/mqaejv9gg/ ls9h7mhkfbons6cqjadbeb5vlobdlcsqfdqo/vz9skfhcmhlxluhhiizykgzgf3oxegndsac3qy+ztnld3n5iyrvbk52uoilolhhnmqa==---- -end RSA PRIVATE KEY-----

?? c) Generate public key

Under the Bin directory, execute the following command:

OpenSSL rsa-in rsa_private_key.pem-pubout-out Rsa_public_key.pem

The newly generated public key file Rsa_public_key.pem will be seen in the bin directory with the following file contents:

-----BEGIN Public KEY-----migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdtd1lksx6ylsaewfi7e/ Ut8krjy9pq7sgykhim9tvidziq5xzyaw8nolzkz1k486mepyg4tsuoaxsbwuplwvuzyfvnuzo7awcigkn16uwtm4nxc/+dwce+ Bhckrllbtwi8l580lte7gxclth8z7ghq59ivhaogbk7fnxlufb4tsqidaqab-----END Public KEY-----

?

? 2.? Client signature

? 2.1?java version Signature Implementation

/** * RSA Signature * * @param content * String to be signed * @param Privatekey * RSA private key string * @param charset * character encoding * @return Signature result * @throws Exception * Signature failed to throw exception */P            Ublic string Rsasign (string content, String Privatekey, String charset) throws Signatureexception {try {            Privatekey Prikey = getPrivateKeyFromPKCS8 ("RSA", New Bytearrayinputstream (Privatekey.getbytes ()));            Signature Signature = signature.getinstance ("Sha1withrsa");            Signature.initsign (Prikey);            if (Stringutils.isempty (charset)) {Signature.update (Content.getbytes ());            } else {signature.update (Content.getbytes (charset));            } byte[] signed = Signature.sign ();        return new String (Base64.encodebase64 (signed)); } catch (Exception e) {throw new Signatureexception ("rsacontent =" + content + "; CharSet = "+ CharSet,e);  }} public Privatekey getPrivateKeyFromPKCS8 (String algorithm, InputStream ins) throws Exception {if (ins = = null | |        Stringutils.isempty (algorithm)) {return null;        } keyfactory keyfactory = keyfactory.getinstance (algorithm);        byte[] Encodedkey = streamutil.readtext (INS). GetBytes ();        Encodedkey = Base64.decodebase64 (Encodedkey);    Return Keyfactory.generateprivate (New Pkcs8encodedkeyspec (Encodedkey)); }

Note: The parameter privatekey is the PEM private key file in the stripped header (-----BEGIN RSA private key-----) and tail (-----end RSA private key-----) as well as the string after the line break.

? 2.2 PHP Signature Implementation

function sign ($content, $rsaPrivateKeyPem) {$priKey = file_get_contents ($rsaPrivateKeyPem); $res = openssl_get_ Privatekey ($priKey); Openssl_sign ($content, $sign, $res); Openssl_free_key ($res); $sign = Base64_encode ($sign); return $sign;}

Note: $rsaPrivateKeyPem is the PEM private key file path

? 2.3 C # Signature implementation (referring to a foreign person's scheme)

Using system;using system.text;using system.security.cryptography;using system.web;using System.IO;namespace aop.api.util{///// RSA Signature Tool class. ///     public class Rsautil {public static string rsasign (string data, String Privatekeypem) {R            Sacryptoserviceprovider RSACSP = Loadcertificatefile (PRIVATEKEYPEM);            byte[] Databytes = Encoding.UTF8.GetBytes (data);            byte[] signaturebytes = Rsacsp.signdata (databytes, "SHA1");        Return convert.tobase64string (signaturebytes); } private static byte[] Getpem (String type, byte[] data) {string PEM = Encoding.UTF8.GetString (d            ATA);            String header = String.Format ("-----BEGIN {0}-----\\n", 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 static RSACryptoServiceProvider loadcertificatefile (string filename) {UsinG (System.IO.FileStream 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 static RSACryptoServiceProvider Decodersaprivatekey (byte[] privkey) {byte[] M            Odulus, E, D, P, Q, DP, DQ, IQ; ---------Set up stream to decode the ASN.1 encoded RSA private key------MemoryStream mem = new Memorystre            AM (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) bi Nr.    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 CSPP                Arameters = 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 static 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) {hi Ghbyte = 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 have 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; }    }}

?

? 3. Server-side Java verification

/** * RSA Verification * * @param content signed contents * @param sign Signature results * @param publickey RSA public key * @param Char Set Character Set * @return verification results * @throws signatureexception Check fails, throw exception */boolean Docheck (String content, String sig N, String PublicKey, String charset) throws Signatureexception {try {publickey PubKey = Getpublickeyfr            omX509 ("RSA", New Bytearrayinputstream (Publickey.getbytes ()));            Signature Signature = signature.getinstance ("Sha1withrsa");            Signature.initverify (PubKey);            Signature.update (getcontentbytes (Content, CharSet));        Return Signature.verify (Base64.decodebase64 (Sign.getbytes ())); } catch (Exception e) {throw new Signatureexception ("RSA authentication Signature [content =" + content + "; CharSet = "+ CharSet +";        Signature = "+ sign +"] An exception occurred! ", e); }} private PublicKey getPublicKeyFromX509 (String algorithm, InputStream ins) throws Nosuchalgorithmexception {try {keyfactory keyfactory = keyfactory.getinstance (algorithm);            StringWriter writer = new StringWriter ();            Streamutil.io (New InputStreamReader (INS), writer);            byte[] Encodedkey = writer.tostring (). GetBytes ();            First base64 decoding Encodedkey = Base64.decodebase64 (Encodedkey);        Return Keyfactory.generatepublic (New X509encodedkeyspec (Encodedkey));        } catch (IOException ex) {//cannot occur} catch (Invalidkeyspecexception ex) {//cannot occur}    return null; } private byte[] Getcontentbytes (string content, String charset) throws Unsupportedencodingexception {if (strin        Gutil.isempty (CharSet)) {return content.getbytes ();    } return Content.getbytes (CharSet); }

?

  • 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.

    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.