Home Backend Development PHP Tutorial PHP Alipay interface RSA verification_PHP tutorial

PHP Alipay interface RSA verification_PHP tutorial

Jul 13, 2016 am 10:37 AM
php interface Alipay

The PHP RSA signature verification problem that has been bothering me for the past two days has finally been solved. Since I didn’t have much contact with RSA before, and the official PHP SDK is not yet available for reference, I took some detours and wrote it here to share with you. .

Although Alipay has not officially provided the relevant SDK, PHP can indeed implement RSA signatures. This is actually very important. Due to unfamiliarity, when encountering difficulties, one often cannot help but wonder whether PHP does not support RSA signatures. Just use MD5, then there will be no motivation to move forward. In fact, to put it bluntly, the only difference between MD5 and RSA signatures is the signature method. Everything else is the same, so I will mainly talk about how to use RSA for signature and signature verification.
First you need to prepare the following things:
The signature verification method openssl_verify has been encapsulated in the openssl extension of php.
If php.ini under Windows needs to enable the Openssl module: extension=php_openssl.dll
Merchant private key:
That is the RSA private key, according to the manual, generate it in the following way:
openssl genrsa -out rsa_private_key.pem 1024
Merchant public key:
That is the RSA private key, according to the manual, generate it in the following way:
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
After generation, according to the manual instructions, you need to upload the public key on the signing platform. It should be noted that all comments and line breaks need to be removed when uploading.
In addition, there are the following commands in the manual:
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt
This command converts the RSA private key to PKCS8 format, which is not required for PHP.
Alipay public key:
According to the manual, obtain it on the signing platform.
If you copy it directly, you will get a string, which needs to be converted as follows;
1) Turn spaces into newlines
2) Add comments
For example, the public key you copied is: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRBMjkaBznjXk06ddsL751KyYt
ztPFg0D3tu7jLqCacgqL+lbshIaItDGEXAMZmKa3DV6Wxy+l48YMo0RyS+dWze4M
UmuxHU/v6tiT0ZTXJN3EwrjCtCyyttdv/ROB3CkheXnTKB76reTkQqg57OWW+m9j
TCoccYMDXEIWYTs3CwIDAQAB, then after conversion:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRBMjkaBznjXk06ddsL751KyYt
ztPFg0D3tu7jLqCacgqL+lbshIaItDGEXAMZmKa3DV6Wxy+l48YMo0RyS+dWze4M
UmuxHU/v6tiT0ZTXJN3EwrjCtCyyttdv/ROB3CkheXnTKB76reTkQqg57OWW+m9j
TCoccYMDXEIWYTs3CwIDAQAB
-----END PUBLIC KEY-----
Save the public key in a file.
Note that this 2048-bit public key should have 9 or 10 lines, not 1 line, otherwise PHP's openssl_pkey_get_public cannot be read, and the result of pub_key_id is false. If there is no -----BEGIN PUBLIC KEY-- --- and -----END PUBLIC KEY----- can be added by yourself and finally saved to an rsa_public_key.pem file.
Okay, now that we have everything, let’s look at the signature function first:
Copy code
1
2 /**
3 * Signature string
4 * @param $prestr String that needs to be signed
5 * return signature result
6*/
7 function rsaSign($prestr) {
8 $public_key= file_get_contents('rsa_private_key.pem');
9 $pkeyid = openssl_get_privatekey($public_key);
10 openssl_sign($prestr, $sign, $pkeyid);
11 openssl_free_key($pkeyid);
12 $sign = base64_encode($sign);
13 return $sign;
14}
15 ?>
Copy code
Note:
1. The content of $prestr is the same as MD5 (see the manual, but does not include the final MD5 password)
2. Merchant private key for signature
3. The final signature needs to be encoded in base64
4. The value returned by this function is the RSA signature of this request.
Signature verification function:
Copy code
1
2 /**
3 * Verify signature
4 * @param $prestr String that needs to be signed
5 * @param $sign signature result
6 * return signature result
7*/
8 function rsaVerify($prestr, $sign) {
9 $sign = base64_decode($sign);
10 $public_key= file_get_contents('rsa_public_key.pem');
11 $pkeyid = openssl_get_publickey($public_key);
12 if ($pkeyid) {
13 $verify = openssl_verify($prestr, $sign, $pkeyid);
14 openssl_free_key($pkeyid);
15 }
16 if($verify == 1){
17 return true;
18 }else{
19 return false;
20 }
21}
22 ?>
Copy code
Note:
1. The content of $prestr is the same as MD5 (see manual)
2.$sign is the binary decoded by base64_decode of the sign parameter returned by the Alipay interface
3. Use Alipay public key for signature verification
4. This function returns a Boolean value, directly telling you whether the signature verification passed
The PHP SDK demo officially provided by Alipay only handles the MD5 encryption method. However, when the Android and iOS terminals request the Alipay encryption method, they can only use the RSA encryption algorithm. At this time, the server-side PHP cannot verify the signature, so Some modifications need to be made to the demo.
1. Modify the alipay_notify.class.php file
verifyNotify function line 46
$isSign = $this->getSignVeryfy($_POST, $_POST["sign"]);
changed to
$isSign = $this->getSignVeryfy($_POST, $_POST["sign"], $_POST["sign_type"]);
verifyReturn function line 83
$isSign = $this->getSignVeryfy($_GET, $_GET["sign"]);
changed to
$isSign = $this->getSignVeryfy($_GET, $_GET["sign"], $_GET["sign_type"]);
getSignVeryfy function line 116
function getSignVeryfy($para_temp, $sign) {
changed to
function getSignVeryfy($para_temp, $sign, $sign_type) {
getSignVeryfy function line 127
switch (strtoupper(trim($this->alipay_config['sign_type']))) {
case "MD5" :
$isSgin = md5Verify($prestr, $sign, $this->alipay_config['key']);
break;
default :
$isSgin = false;
}
changed to
switch (strtoupper(trim($sign_type))) {
case "MD5" :
$isSgin = md5Verify($prestr, $sign, $this->alipay_config['key']);
break;
case "RSA" :
$isSgin = rsaVerify($prestr, $sign);
break;
default :
$isSgin = false;
}
2. Create a new alipay_rsa.function.php file
Copy code
1
2 /* *
3 * RSA
4 * Details: RSA encryption
5 * Version: 3.3
6 * Date: 2014-02-20
7 * Description:
8 * The following code is only a sample code provided to facilitate merchant testing. Merchant can write it according to the technical documentation according to the needs of their own website. It is not necessary to use this code.
9 * This code is only for learning and researching the Alipay interface and is only provided as a reference.
10 */
11 /**
12 * Signature string
13 * @param $prestr String that needs to be signed
14 * return signature result
15*/
16 function rsaSign($prestr) {
17 $public_key= file_get_contents('rsa_private_key.pem');
18 $pkeyid = openssl_get_privatekey($public_key);
19 openssl_sign($prestr, $sign, $pkeyid);
20 openssl_free_key($pkeyid);
21 $sign = base64_encode($sign);
22 return $sign;
23}
24 /**
25 * Verify signature
26 * @param $prestr String that needs to be signed
27 * @param $sign signature result
28 * return signature result
29*/
30 function rsaVerify($prestr, $sign) {
31 $sign = base64_decode($sign);
32 $public_key= file_get_contents('rsa_public_key.pem');
33 $pkeyid = openssl_get_publickey($public_key);
34 if ($pkeyid) {
35 $verify = openssl_verify($prestr, $sign, $pkeyid);
36 openssl_free_key($pkeyid);
37 }
38 if($verify == 1){
39 return true;
40 }else{
41 return false;
42 }
43}
44 ?>
Copy code
The last thing I want to say is that the official manual is basically correct, but there are some places that are not very detailed. You must refer to it more when developing. That's roughly it. I wish everyone good luck.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/735876.htmlTechArticleThe PHP RSA signature verification problem that has been bothering these two days has finally been solved. Since I didn’t have much contact with RSA before, In addition, there is no official PHP SDK for reference yet, so I took some detours and wrote...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? Mar 31, 2025 pm 11:51 PM

Problem Description When calling Alipay EasySDK using PHP, after filling in the parameters according to the official code, an error message was reported during operation: "Undefined...

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

See all articles