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fg+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 代码部分一致。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.
