Maison > Article > développement back-end > php RSA 加密 与java加密 同步
<?phpclass encrypt{ var $pub_key; function redPukey() { $pubKey = "MIIDhzCCAm+gAwIBAgIGASYISh96MA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDElMCMGA1UECwwcQWxsaW5wYXkgUHJpbWFyeSBDZXJ0aWZpY2F0ZTAeFw0xMDAxMDcxMDE3NDBaFw0zMDAxMDIxMDE3NDBaMGQxCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDEqMCgGA1UECwwhQWxsaW5wYXkgRGlnaXRhbCBTaWduIENlcnRpZmljYXRlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEv2q2/xN5PF0dLn1vhIaVlyWsvJFVFxWgH7sQBObzYbZXOOVzoQpmXuSFOrF0/ol4Okd/2OGfdXUUFSUZfzAQOT1Wmjupec7z2V6l4/PT7aOg6t/MJwU9aW9Iw+AFzM1vnLOXdTlWVLZbtB7IiJ/HhfwBDkyvhp1zNYoAPrwC5QIDAQABo4HHMIHEMB0GA1UdDgQWBBQlWQA//YbuEdfE1yP+PpnokDO8WDCBjgYDVR0jBIGGMIGDgBSBWR3Bvx8To7TrecKhCM4smeabN6FjpGEwXzELMAkGA1UEBhMCQ04xKTAnBgNVBAoMIEFsbGlucGF5IE5ldHdvcmsgU2VydmljZXMgQ28uTHRkMSUwIwYDVQQLDBxBbGxpbnBheSBQcmltYXJ5IENlcnRpZmljYXRlggYBJghKHowwEgYDVR0TAQH/BAgwBgEB/wIBADANBgkqhkiG9w0BAQUFAAOCAQEATzT9GuAmAXLSWpoGc0F7Km7DPMWvSAkq8ckJLftF0/lB3JTR6QT5rsTnQHCdRU7SJX+eLNwhJQdRg34dPJAI2z/HpgGu7tW7pdsHjCjlVae3I64h2OzYBGXdtdRyPmyXfBOgXUfqtH0Fg+1QqsRmcRugywjZH8ZQAVYm0TkVJmdBknPp60bJ2gE/nj0w6VaSL6HMAQ+A7AVne3NDreBXepMHgiFqiqMHrZFBQCgTSR1UwZoT8hwXaaUgwf2h9l/D2QOGCD8G3sRKfMsH3clkehXbprWPNk3uww7dCT0pGz845AyKzCmRK60Z/NOgMG5X+f+JmugsS/bKYwjetXHg9Q=="; $pem = chunk_split($pubKey,64,"\n");//转换为pem格式的公钥 $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; } /* 签名数据: data:utf-8编码的订单原文, privatekeyFile:私钥路径 passphrase:私钥密码 返回:base64转码的签名数据 */ function sign($data) { //证书路径 $privatekeyFile="../cer/testMemberKey.pfx"; //证书私钥 $passphrase="testMemberKey"; $signature = ''; $privateKey; $signedMsg; $pkcs12 = file_get_contents($privatekeyFile); if (openssl_pkcs12_read($pkcs12, $certs, "testMemberKey")) { $privateKey = $certs['pkey']; } if (openssl_sign($data, $signedMsg, $privateKey,OPENSSL_ALGO_SHA1)) { $signedMsg= strtoupper(bin2hex($signedMsg));//这个看情况。有些不需要转换成16进制,有些需要base64编码。看各个接口 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,OPENSSL_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(); //公钥加密 $userName= $dateEncrypt->pubkeyEncrypt("测试数据",$userName,$pukey); echo $userName; //私钥加密 $signBytes=$dateEncrypt->sign($signSrc); echo $signBytes;?>
参考php 手册?>函数拓展?>加密拓展
php RSA 加密 加密结果每次都会不一样,这是正确的。 跟java 有区别。java 结果不会变,但是java 能解出来。
证书都需要转换下 pem 格式才能使用。
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.IllegalBlockSizeException;import javax.crypto.NoSuchPaddingException;import org.bouncycastle.jce.provider.BouncyCastleProvider;public class CertSignUtil { /** * 测试方法 从keystore中获得公私钥对 * * @param filePath * keystore文件路径 * @param keyStorePassword * keystore 密码 * @param masterPassword * 私钥主密码,可以和keystore密码相同也可不同 * @param alias * 密钥对别名 */ public static KeyPair getKeyFromKeyStore(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()); // 也可以从keyStore中直接读公钥证书,无须通过私钥转换 // 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; } /** * 使用私钥证书签名 * * @param priKey * 私钥对象 * @param plainText * 明文文本的字节数组 * @param encAlg * 加密算法 * @param signAlg * 签名算法 * @return 加密后的密文串 * * @see verifyByPubKey */ public static byte[] signByPriKey(Key priKey, byte[] srcBytes, String signAlg) { // 签名 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("私钥签名 - 无效算法:"); } catch (InvalidKeyException e) { // LoggerUtil.error("私钥签名 - 无效的密钥:"); } catch (SignatureException e) { // LoggerUtil.error("私钥签名 - 签名异常:"); } return signBytes; } /** * Byte数组转十六进制字符串,字节间不用空格分隔 * * @param b * @return */ public static String bytes2HexString(byte[] b) { String ret = ""; for (int i = 0; i byte[]{0x2B, 0x44, 0xEF, * 0xD9} * * @param src * 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 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 <br> <pre name="code" class="sycode">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 后台系统管理//20141013//zhd//testMemberKey.keystore", "testMemberKey", "testMemberKey", "testMemberKey"); Key pubKey = CertSignUtil.getPubKeyFromCertFile("E://Jason's Work File//AllinPay//Boss 后台系统管理//20141013//zhd//TLCert4Sign_test.cer"); System.out.println(pubKey); byte[] encBytes = CertSignUtil.encByPubKey(pubKey, "测试数据".getBytes(), "RSA"); // System.out.println("aaaaaa" + new String(encBytes)); byte[] aaa = CertSignUtil.signByPriKey(kp.getPrivate(), "测试数据".getBytes(), Constants.SHA1_WITH_RSA); System.out.println(aaa); String signMsg = CertSignUtil.bytes2HexString(aaa); System.out.println(signMsg); byte[] encByte = CertSignUtil.encByPubKey(pubKey, "测试数据".getBytes(), "RSA"); String signMsg1 = CertSignUtil.bytes2HexString(encByte); System.out.println(signMsg1); }}
java RSA 默认的补码方式是 OPENSSL_PKCS1_PADDING 所以需要跟上面 php 代码部分一致。