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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles