PHP RSA Encryption and Java encryption to cross, Java decryption

Source: Internet
Author: User
Tags base64 string format

<?phpclass encrypt{var $pub _key; function Redpukey () {$pubKey = "Miidhzccam+gawibagigasyish96ma0gcsqgsib3dqebbquamf8xczajbgnvbaytaknomskwjwy Dvqqkdcbbbgxpbnbhesbozxr3b3jrifnlcnzpy2vzienvlkx0zdelmcmga1uecwwcqwxsaw5wyxkguhjpbwfyesbdzxj0awzpy2f0ztaefw0xmdaxmdcxmde3 Ndbafw0zmdaxmdixmde3ndbamgqxczajbgnvbaytaknomskwjwydvqqkdcbbbgxpbnbhesbozxr3b3jrifnlcnzpy2vzienvlkx0zdeqmcgga1uecwwhqwxsa w5wyxkgrglnaxrhbcbtawduienlcnrpzmljyxrlmigfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdev2q2/ xn5pf0dln1vhiavlywsvjfvfxwgh7sqbobzybzxoovzoqpmxusforf0/ol4okd/2ogfdxuufsuzfzaqot1wmjupec7z2v6l4/pt7aog6t/ mjwu9aw9iw+afzm1vnloxdtlwvlzbtb7iij/hhfwbdkyvhp1znyoaprwc5qidaqabo4hhmihemb0ga1uddgqwbbqlwqa//ybuedfe1yp+ Ppnokdo8wdcbjgydvr0jbiggmigdgbsbwr3bvx8to7treckhcm4smeabn6fjpgewxzelmakga1uebhmcq04xktanbgnvbaomiefsbglucgf5ie5ldhdvcmsgu 2vydmljzxmgq28uthrkmsuwiwydvqqldbxbbgxpbnbhesbqcmltyxj5ienlcnrpzmljyxrlggybjghkhowwegydvr0taqh/bagwbgeb/ wibadanbgkqhkig9w0baqufaaocaqeatzt9guamaxlswpogc0f7km7dpmwvsakq8ckjlftf0/lb3jtr6qt5rstnqhcdru7sjx+elnwhjqdrg34dpjai2z/hpggu7tw7pdshjcjlvae3i64h2ozybgxdtdrypmyxfbogxufqth0fg+ 1qqsrmcrugywjzh8zqavym0tkvjmdbknpp60bj2ge/nj0w6vasl6hmaq+ a7avne3ndrebxepmhgifqiqmhrzfbqcgtsr1uwzot8hwxaaugwf2h9l/          d2qogcd8g3srkfmsh3clkehxbprwpnk3uww7dct0pgz845aykzcmrk60z/nogmg5x+f+jmugss/bkywjetxhg9q== "; $pem = Chunk_split ($pubKey, "\ n"), or//convert the public key to PEM format $pem = "-----BEGIN CERTIFICATE-----\ n". $pem. "          -----END CERTIFICATE-----\ n ";         $publicKey = Openssl_pkey_get_public ($PEM); $certificateCAcerContent = file_get_contents ("..         /cer/cert_usercenter/tlcert4sign_test.cer ");         $pub _key = Openssl_get_publickey ($certificateCAcerContent);          return $pub _key;    return $publicKey; }/* Signature data: Data:utf-8 encoded order text, Privatekeyfile: Private key path passphrase: Private key password return: Base64 transcoding signature Data */function S IGN ($DATA) {//certificate path $privatekeyFile = ":       /cer/testmemberkey.pfx ";       Certificate private Key $passphrase = "Testmemberkey"; $Signature = ";       $privateKey;       $SIGNEDMSG;       $PKCS = file_get_contents ($privatekeyFile);      if (Openssl_pkcs12_read ($PKCS, $certs, "Testmemberkey")) {$privateKey = $certs [' Pkey ']; } if (Openssl_sign ($data, $SIGNEDMSG, $privateKey, OPENSSL_ALGO_SHA1)) {$SIGNEDMSG = Strtoupper (Bin2Hex ($sign EDMSG));//This looks at the situation. Some do not need to be converted into 16, some require Base64 encoding.      Look at each interface return $SIGNEDMSG;        }//$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);     return $privateKey; } function Pubkeyencrypt ($data, $panText, $pubkey) {openssl_public_encrypt ($data, $panText, $pubkey, Openss        l_pkcs1_padding);        Return Strtoupper (Bin2Hex ($panText));     } function GetBytes ($string) {$bytes = array ();     for ($i = 0; $i < strlen ($string); $i + +) {$bytes [] = Ord ($string [$i]);      } return $bytes; }}?>

<?phprequire_once ("encrypt.php"); $dateEncrypt =new Encrypt (); $pukey = $dateEncrypt->redpukey (); Public Key Cryptography $userName = $dateEncrypt->pubkeyencrypt ("test Data", $userName, $pukey);  echo $userName;  Private key Encryption $signBytes = $dateEncrypt->sign ($SIGNSRC); Echo $signBytes;? >


Refer to PHP Manual, function development, encryption extension


PHP RSA Encryption results will be different every time, this is correct. is different from Java. Java results do not change, but Java can solve them.


Certificates are required to be converted to the PEM format for use.





Java section

Package Com.allinpay.common.util;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.security.invalidkeyexception;import Java.security.key;import Java.security.keypair;import Java.security.keystore;import Java.security.keystoreexception;import Java.security.nosuchalgorithmexception;import Java.security.privatekey;import Java.security.PublicKey;import Java.security.signature;import Java.security.signatureexception;import java.security.UnrecoverableKeyException; Import Java.security.cert.certificate;import Java.security.cert.certificateexception;import Java.security.cert.certificatefactory;import Java.security.cert.x509certificate;import Javax.crypto.badpaddingexception;import Javax.crypto.cipher;import Javax.crypto.illegalblocksizeexception;import Javax.crypto.nosuchpaddingexception;import Org.bouncycastle.jce.provider.bouncycastleprovider;public Class    Certsignutil {/** * Test method obtains a public private key pair * * @param filePath from the KeyStore * KeyStore File path * @param keystorepassword * keystore Password * @param masterpassword * The private key master password can be the same as the keystore password * @param alias * Key pair alias */public static KeyPair Getkeyfromkey  Store (String FilePath, String Keystorepassword, String Masterpassword, string alias) {KeyPair KeyPair =        Null            try {KeyStore KeyStore = keystore.getinstance (Keystore.getdefaulttype ());            Keystore.load (New FileInputStream (FilePath), Keystorepassword.tochararray ());            Key key = Keystore.getkey (alias, Masterpassword.tochararray ());            The public key certificate can also be read directly from the KeyStore without the need for a private key conversion//Certificate cert = keystore.getcertificate (alias);            PublicKey PubKey = Cert.getpublickey ();                if (key instanceof Privatekey) {Certificate cert = keystore.getcertificate (alias);  KeyPair = new KeyPair (Cert.getpublickey (), (Privatekey) key);          } Privatekey Privatekey = Keypair.getprivate ();        PublicKey PublicKey = Keypair.getpublic ();        } catch (Keystoreexception e) {e.printstacktrace ();        } catch (Certificateexception e) {e.printstacktrace ();        } catch (NoSuchAlgorithmException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();        } catch (Unrecoverablekeyexception e) {e.printstacktrace ();    } return KeyPair;      /** * signed with a private key certificate * * @param prikey * Private Key Object * @param plaintext * Clear text byte array * @param encalg * Encryption Algorithm * @param SIGNALG * Signature Algorithm * @return Encrypted cipher String * * @        See Verifybypubkey */public static byte[] Signbyprikey (Key prikey, byte[] srcbytes, String signalg) {        Signature byte[] signbytes = null; try {Signature sign = signature.getinstance (siGnalg, New Bouncycastleprovider ());            Sign.initsign ((Privatekey) prikey);            Sign.update (srcbytes);        Signbytes = Sign.sign ();        } catch (NoSuchAlgorithmException e) {///Loggerutil.error ("Private key signature-Invalid algorithm:");        } catch (InvalidKeyException e) {///Loggerutil.error ("Private key signature-invalid key:");        } catch (Signatureexception e) {///Loggerutil.error ("Private key signature-signature exception:");    } return signbytes; }/** * byte array to hexadecimal string, separated by spaces between bytes * * @param b * @return */public static string bytes2hexstring (byte[] b)        {String ret = "";            for (int i = 0; i < b.length; i++) {String hex = integer.tohexstring (B[i] & 0xFF);            if (hex.length () = = 1) {hex = ' 0 ' + hex;        } ret + = Hex.touppercase ();    } return ret;   }/** * will specify the string src, converted to 16 binary forms per two characters such as: "2b44efd9"--byte[]{0x2b, 0x44, 0xEF, * 0xd9}  * * @param src * string Format Strings * @return byte[] * * public static byte[] Hexstring2bytes (Str        ing src) {if (Src.length ()% 2! = 0) {src = src + "0";        } byte[] ret = new Byte[src.length ()/2];        byte[] tmp = Src.getbytes ();        for (int i = 0; I < (Src.length ()/2); i++) {Ret[i] = unitebytes (Tmp[i * 2], Tmp[i * 2 + 1]);    } return ret;            }/** * Matches two ASCII words into one byte, such as: "EF"-0xEF * * @param src0 * byte * @param src1 * BYTE * @return byte */public static byte Unitebytes (byte src0, byte src1) {byte _b0 = byte.        Decode ("0x" + new String (new byte[] {src0})). Bytevalue ();                _b0 = (byte) (_b0 << 4),//left 4bit, becomes 8-bit high 4 bit byte _b1 = Byte.decode ("0x" + new String (new byte[] {SRC1}))    . Bytevalue ();//Do not move left, keep at low 4 bit byte ret = (byte) (_b0 ^ _b1);//Bitwise XOR can return RET;   } /** * Verify signature with public key * * @param pubkey * Public key * @param srcbytes * Signature Original string byte array * @ Param signbytes * Signature string byte array * @param SIGNALG * Signature Algorithm * @return Verification Result true = success false = Not Success * * @see Signbyprikey */public static Boolean Verifybypubkey (Key PubKey, byte[] Srcbytes, b        Yte[] signbytes, String signalg) {Boolean result = false;            try {Signature sign = signature.getinstance (Signalg, New Bouncycastleprovider ());            Sign.initverify ((PublicKey) pubkey);            Sign.update (srcbytes);        result = Sign.verify (signbytes);        } catch (NoSuchAlgorithmException e) {//Loggerutil.error ("Public key check-invalid algorithm:");        } catch (InvalidKeyException e) {///Loggerutil.error ("Public key check-invalid key:");        } catch (Signatureexception e) {//Loggerutil.error ("Public key Check-signature exception:");    } return result; }/** * FROMCertificate file reads Public key * * @param certfilepath * Public Key Certificate path * @return Public key * *        Omcertfile (String certfilepath) {PublicKey key = null;            try {certificatefactory factory = certificatefactory. getinstance ("the");            FileInputStream fis = new FileInputStream (Certfilepath);            X509Certificate cert = (x509certificate) factory. Generatecertificate (FIS);        Key = Cert.getpublickey ();            } catch (FileNotFoundException e) {///Loggerutil.error ("Read public key from certificate file-certificate file does not exist:");        Loggerutil.error (e);            } catch (Certificateexception e) {///Loggerutil.error ("Read public key from certificate file-key Read exception:");        Loggerutil.error (e);    } return key; }///**//* Through Merchant Public key Certificate verification//* @param CERTSTR certificate information, such as Certstyle = 1 then CERTSTR is the certificate Base64 content, such as certstyle=0//CERTSTR Save path for certificate//* @param certstyle Certificate get format 1 for Base64 encoded certificate text from DB, 2 for from specified pathEvidence File//* @param srcmsg Signature Source string//* @param signmsg Signature string//* @return//*//public static Boolean VERIFYBYC    ERT (string certstr, int certstyle, string//Srcmsg, String signmsg) {//////if (Certstyle = 0) {//try{ return Verifybypubkey (//Getpubkeyfromstr (CERTSTR),//Srcmsg.getbytes ("UTF-8"),//Hexstring2bytes (SIGNMS    g),//SECURITYUTIL.MCHT_SIGN_ALG);    }catch (Exception e) {//Loggerutil.error (e);    return false;    }////}else{//Loggerutil.error ("Invalid certificate storage format specified in parameter");    return false;            }////}/** * Use public key encryption * * @param PubKey * Public Key Object * @param plaintext * byte array of plaintext text * @param ENCALG * Encryption algorithm * @return Encrypted cipher String * * @see Decbyprikey */PU        Blic static byte[] Encbypubkey (Key PubKey, byte[] plaintext, String encalg) {//encrypt byte[] encbytes = null; try {Cipher Cipher = cipher.getinstance (encALG, New Bouncycastleprovider ());            Cipher.init (Cipher.encrypt_mode, PubKey);        Encbytes = cipher.dofinal (plaintext);        } catch (NoSuchAlgorithmException e) {///Loggerutil.error ("Public Key Cryptography-Invalid algorithm:");        } catch (InvalidKeyException e) {///Loggerutil.error ("Public Key Cryptography-Invalid Key:");        } catch (Illegalblocksizeexception e) {///Loggerutil.error ("Public key cryptography-illegal chunk size:");        } catch (Nosuchpaddingexception e) {///Loggerutil.error ("Public Key cryptography-Bad Fill format:");        } catch (Badpaddingexception e) {///Loggerutil.error ("Public Key Cryptography-padding Exception:");    } return encbytes; }}

Package Com.allinpay.user;import Java.security.key;import Java.security.keypair;import Com.allinpay.common.util.certsignutil;import Com.allinpay.common.util.constants;public class Test {public static void Main (string[] args) {KeyPair KP = certsignutil. Getkeyfromkeystore ("Testmemberkey.keystore", "        Testmemberkey "," Testmemberkey "," Testmemberkey ");        Key PubKey = Certsignutil.getpubkeyfromcertfile ("Tlcert4sign_test.cer");        System.out.println (PubKey);        byte[] encbytes = Certsignutil.encbypubkey (PubKey, "test Data". GetBytes (), "RSA");        System.out.println ("aaaaaa" + new String (encbytes));        Byte[] aaa = Certsignutil.signbyprikey (Kp.getprivate (), "test Data". GetBytes (), Constants.sha1_with_rsa);        System.out.println (AAA);        String signmsg = certsignutil.bytes2hexstring (AAA);        System.out.println (SIGNMSG);        byte[] Encbyte = Certsignutil.encbypubkey (PubKey, "test Data". GetBytes (), "RSA"); String SIGNMSG1 = Certsignutil.bytEs2hexstring (Encbyte);    System.out.println (SIGNMSG1); }}

The default complement for Java RSA is openssl_pkcs1_padding so it needs to be consistent with the PHP code section above.




PHP RSA Encryption and Java encryption to cross, Java decryption

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.