PHP, C # and JAVARSA signature and signature

Source: Internet
Author: User
Tags modulus openssl rsa pkcs12
PHP, C #, and JAVARSA signatures and signatures are found on the Internet. To make a contribution, we must repost and express our gratitude to Zhuo Ermei for her selfless dedication. 1) the signature algorithm uses SHA1withRSA. 2) the signed data bit base64 encoded ciphertext string. 3) the formats of private keys signed in the three environments are different. openssl is required for conversion. ----------------------------------- PHP, C # and JAVARSA signatures and signatures

This feature has found a lot of information online. To make a contribution, we must repost and express our gratitude to Zhuo Ermei for her selfless dedication.

1) the signature algorithm uses SHA1withRSA.

2) the signed data bit base64 encoded ciphertext string.

3) the formats of private keys signed in the three environments are different. openssl is required for conversion.

------------------------------------------

JAVA signature:

1) obtain the. key private key from the pfx certificate containing 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 when exporting) MAC verified OKEnter PEM pass phrase :( a pem certificate Password with at least four characters in length) Verifying-Enter PEM pass phrase :( confirm the pem certificate Password once) f: \ openssl-0.9.8k_WIN32 \ bin> openssl pkcs8-topk8-inform PEM-outform DER-in f: \ certs \ zhuo. pem-out f: \ certs \ zhuo_der.key-nocryptEnter pass phrase for f: \ certs \ zhuo. pem :( enter the pem certificate password)
??

The. KeyFile is the private key file required for JAVA signature.

2) generate a public key: directly export the certificate with the extension cer in X.509 format from IE.

?

?

3) signature verification:

?

// Signature:/*** function description: signature data * created by zhuoyueping 2013-8-17 * modified by zhuoyueping 2013-8-17 * Description: * @ param content: original Signature * @ param keyfile: private key file. key path * @ param @ return * @ param @ throws Exception * @ return String: base64 signature * @ throws */public String sign (String content, String keyfile) throws Exception {File file = new File (keyfile); // address of the keyfile key File FileInputStream in; in = new F IleInputStream (file); ByteArrayOutputStream bout = new ByteArrayOutputStream (); byte [] tmpbuf = new byte [1024]; int count = 0; while (count = in. read (tmpbuf ))! =-1) {bout. write (tmpbuf, 0, count); tmpbuf = new byte [1024];} in. close (); KeyFactory keyFactory = KeyFactory. getInstance ("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec (bout. toByteArray (); rsw.vatekey privateKey = (rsw.vatekey) keyFactory. generatePrivate (privateKeySpec); Signature dsa = Signature. getInstance ("SHA1withRSA"); // use SHA1withRSA to encrypt dsa. initSign (privateKey); dsa. update (content. getBytes ("UTF-8"); // The String to which voucher needs to be encrypted must be a byte type byte [] sig = dsa. sign (); String rtnValue = new String (Base64.encode (sig); return rtnValue ;}/***

* Verify the signature *

** @ Param data original byte * @ param sign data signature [BASE64] * @ param certificatePath certificate storage path * @ return * @ throws Exception */public static boolean verifySign (byte [] data, string sign, String certificatePath) throws Exception {// obtain the certificate X509Certificate x509Certificate = (certificate) getCertificate (certificatePath); return verifySign (data, sign, signature );} private static boolean verifySign (byte [] data, String sign, X509Certificate x509Certificate) throws Exception {PublicKey publicKey = 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 containing 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 generated in this step. the key file is the private key file required for the C # signature.
?

(2) public key generation: x509 certificates in binary format are the same in java mode.3) signature and signature:

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 the signature //////Original article: UTF8 encoding///Signature: base64 encoded bytes///Public key path///
 
  
Verification result
 Public bool Verify (String OriginalString, String SignatureString, String publicKeyPath) {// transcode base64 signature data to 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 the signature //////Original article: UTF8 encoding///Certificate path: D:/certs/mycert. key///
 
  
Signature Verification
 Public string Sign (string data, string privateKeyPath) {RSACryptoServiceProvider rsaCsp = LoadCertificateFile (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 = Strin G. 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. 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 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 MemoryStream (privke Y); 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 are 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 (bin R); 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 = new CspParameters (); CspParameters. flags = CspProviderFlags. useMachineKeyStore; RSACryptoServiceProvider RSA = new RSACryptoServicePr Ovider (1024, 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 CT 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 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 ;}}}

?

PHP signature:

1) obtain the. key private key from the pfx certificate containing the public/private key: the certificate at C # is consistent.

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 signature:

/* Signature data: original order of UTF-8 encoding, privatekeyFile: private key path passphrase: private key password return: base64 transcoding signature data */function sign ($ data, $ privatekeyFile, $ passphrase) {$ signature = ''; $ privatekey = Encrypt (file_get_contents ($ privatekeyFile), $ passphrase); $ res = Encrypt ($ privatekey ); openssl_sign ($ data, $ signature, $ res); openssl_free_key ($ res); return base64_encode ($ signature);}/* signature verification: data: Original signature: signature publicKeyPath: public key path return: signature result. true indicates that the signature is successfully verified, and false indicates that the signature Fails. */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 ;}

? * For PHP, you need to pay attention to the version and the import of some packages. If an error is reported, google will try again ~~

?

?

?

?

?

?

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.