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8ZQAVYm0TkVJmdBknPp60bJ2gE/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 代码部分一致。

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
