PhpRSA encryption and java encryption synchronization
RedPukey (); // public key encryption $ userName = $ dateEncrypt-> pubkeyEncrypt ("test data", $ userName, $ pukey); echo $ userName; // private key encryption $ signBytes = $ dateEncrypt-> sign ($ signSrc); echo $ signBytes;?>
Refer to the php manual?> Function expansion?> Encryption expansion
The encryption results of php RSA encryption are different each time. This is correct. It is different from java. The java result will not change, but java can solve it.
Certificates must be converted to the pem format for use.
Java
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. illegalBlockSizeExcepti On; import javax. crypto. noSuchPaddingException; import org. bouncycastle. jce. provider. bouncyCastleProvider; public class CertSignUtil {/*** test method: obtain the public/private key pair from the keystore ** @ param filePath * keystore file path * @ param keyStorePassword * keystore password * @ param masterPassword * private key master password, it can be the same or different from the keystore password * @ param alias * key pair alias */public static KeyPair getKeyFromKeyStore (String filePath, String keyStorePassword, Stri Ng 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 (); // You can also directly read the public key Certificate from the keyStore without private key conversion. // Certificate cert = keyStore. getCertificate (alias); // PublicKey pubKey = cert. getPublicK Ey (); 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. printSt AckTrace ();} catch (IOException e) {e. printStackTrace ();} catch (UnrecoverableKeyException e) {e. printStackTrace ();} return keyPair ;} /*** sign using the private key certificate ** @ param priKey * private key object * @ param plainText * byte array of plainText text * @ param encAlg * encryption algorithm * @ param signAlg * signature Algorithm * @ return encrypted ciphertext string ** @ see verifyByPubKey */public static byte [] signByPriKey (Key priKey, byte [] srcBytes, String signAlg) {// signature byte [] sig NBytes = 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;}/*** convert the Byte array to a hexadecimal string, do not separate byte spaces ** @ 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;}/*** converts the specified string src to a hexadecimal form separated by two characters, for example: "2B44EFD9" --> byte [] {0x2B, 0x44, 0xEF, * 0xD9 }* * @ Param src * String format String * @ return byte [] */public static byte [] hexString2Bytes (String 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;}/*** combines two ASCII characters into one byte, for example: "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); // shifts 4 bits left to the 4-bit byte _ b1 = Byte in 8 bits. decode ("0x" + new String (new byte [] {src1 })). byteValue (); // do not move left, keep at low 4 bytes ret = (byte) (_ b0 ^ _ b1); // return ret by bit or by bit ;} /*** use the public key to verify the signature ** @ param pubKey * Public Key * @ param srcBytes * sign the original string byte array * @ param signBytes * signature string byte array * @ param signAlg * signature algorithm * @ return verification result true = success false = unsuccessful ** @ see signByPriKey */public static boolean verifyByPubKey (Key pubKey, byte [] srcBytes, byte [] 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 verification-invalid algorithm:");} catch (InvalidKeyException e) {// LoggerUtil. error ("public key verification-invalid key:");} catch (SignatureException e) {// LoggerUtil. error ("public key signature verification-signature exception:");} return result ;} /*** read the public Key from the certificate file ** @ param certFilePath * public key certificate path * @ return public Key */public static key getPubKeyFromCertFile (String certFilePath) {PublicKey Key = null; try {CertificateFactory factory = CertificateFactory. getInstance ("X.509"); FileInputStream FCM = new FileInputStream (certFilePath); X509Certificate cert = (X509Certificate) factory. generateCertificate (FCM); 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 ("public key read from certificate file-key read exception:"); // LoggerUtil. error (e);} return key;} // ** // use the merchant's public key certificate to verify the certificate information. // * @ param certStr, for example, if certStyle = 1, certStr indicates the certificate base64 Content, for example, certStyle = 0 //, certStr is the certificate storage path. // * @ param certStyle: certificate format 1: obtain base64 encoded certificate text from the database, 2. obtain the certificate file from the specified path // * @ param srcMsg signature Source string // * @ param signMsg signature string // * @ return // * // public static boolean verifyByCert (String certStr, int certStyle, String // srcMsg, String signMsg) {// if (certStyle = 0) {// try {// return verifyByPubKey (// getPubKeyFromStr (certStr), // srcMsg. getBytes ("UTF-8"), // hexString2Bytes (signMsg), // SecurityUtil. MCHT_SIGN_ALG); //} catch (Exception e) {// LoggerUtil. error (e); // return false; //} else {// LoggerUtil. error ("invalid certificate storage format specified in the 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 ciphertext string ** @ see decByPriKey */public static byte [] encByPubKey (Key pubKey, byte [] plainText, String encAlg) {// encrypted 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 encryption-invalid algorithm:");} catch (InvalidKeyException e) {// LoggerUtil. error ("public key encryption-invalid key:");} catch (IllegalBlockSizeException e) {// LoggerUtil. error ("public key encryption-invalid part size:");} catch (NoSuchPaddingException e) {// LoggerUtil. error ("public key encryption-incorrect filling format:");} catch (BadPaddingException e) {// LoggerUtil. error ("public key encryption-filling 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 ("E: // Jason's Work File // AllinPay // Boss background system management // 20141013 // zhd // testMemberKey. keystore "," testMemberKey "); Key pubKey = CertSignUtil. getPubKeyFromCertFile ("E: // Jason's Work File // AllinPay // Boss background System management // 20141013 // zhd // 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 );}}
Java RSA uses OPENSSL_PKCS1_PADDING by default, so it must be consistent with the above php code.