PHP Payment Treasure Interface RSA authentication

Source: Internet
Author: User
Tags end file copy interface openssl openssl rsa php file string trim
These two days have been plagued PHP RSA signature Verification problem finally resolved, because the RSA contact is not much, plus the official has not yet PHP SDK available for reference, so took some detours, write here and share.     Although Alipay official has not provided relevant sdk,php can indeed achieve the signature of RSA way, this is very important, because unfamiliar, in the face of difficulties, often involuntarily think of whether PHP does not support RSA signature, simply with MD5 got, So there is no momentum to move forward. In fact, the MD5 and RSA signature, the difference is just the way the signature, the other is the same, so I am here to talk about how to use RSA signature and verification.        First you need to prepare the following things:     PHP OpenSSL expansion has been encapsulated in the verification method openssl_verify.     If the php.ini required to open the OpenSSL module in Windows: Extension=php_openssl.dll       Merchant private key:     The RSA private key, as per the manual, is generated in the following manner:       OpenSSL genrsa-out Rsa_private_key.pem 1024        Merchant public key: &N Bsp   That is, the RSA private key, according to the manual, is generated in the following manner:     OpenSSL rsa-in rsa_private_key.pem-pubout-out Rsa_public_key.pem   &NBSP ;   After the production, according to the manual instructions, need to upload the public key on the signing platform, it is necessary to note that when the upload needs to be all the comments and lines to remove.         Additional manuals also have the following commands:     OpenSSL pkcs8-topk8-inform pem-in rsa_private_key.pem-outform P Em-nocrypt       This command converts the RSA private key to the PKCS8 format, which is not required for PHP.         Alipay public key:     In accordance with the manual, on the signing platform to obtain.     If you copy it directly, you'll get a string that needs to be converted;     1 To change a space into a newline     2) Add a note     For example, the public key you copied is: MIGF Ma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdrbmjkabznjxk06ddsl751kyyt   ztpfg0d3tu7jlqcacgql+ lbshiaitdgexamzmka3dv6wxy+l48ymo0rys+dwze4m umuxhu/v6tit0ztxjn3ewrjctcyyttdv/rob3ckhexntkb76retkqqg57oww+m9j Tcoccymdxeiwyts3cwidaqab, after which the conversion is:    -----BEGIN public KEY-----  Migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdrbmjkabznjxk06ddsl751kyyt Ztpfg0d3tu7jlqcacgql+lbshiaitdgexamzmka3dv6wxy +l48ymo0rys+dwze4m umuxhu/v6tit0ztxjn3ewrjctcyyttdv/rob3ckhexntkb76retkqqg57oww+m9j TCoccYMDXEIWYTs3CwIDAQAB---- -end Public Key-----    Keep the key in the file.     Note that this is a 2048-bit public key should be 9 or 10 lines, not 1 lines, otherwise the PHP openssl_pkey_get_public cannot read, pub_key_id result is false, if there is no-----BEGIN The public key-----and-----End Public key-----can be added to themselves and finally saved to a RSA_PUBLIC_KEY.PEM file.   Well, now that you've got everything, look at the signature function:   Copy code  1 <?php  2/**  3  * signature string  4  * @param $prestr The string that needs to be signed  5  * return signature result  6  */ 7 function rsasign ($prestr) { 8   & nbsp $public _key= file_get_contents (' Rsa_private_key.pem ');  9     $pkeyid = Openssl_get_privatekey ($public _key);     Openssl_sign ($prestr, $sign, $pkeyid);     Openssl_free_key ($pkeyid);     $sign = Base64_encode ($sign);     return $sign; ?> Copy Code Note: 1. $PRESTR content is the same as MD5 (see the manual, but not the last MD5 password) 2. The private key for the signature is 3. The final signature needs to be Base64 encoded 4. The value returned by this function is the RSA signature for this request.   Verification Function:   Copy code  1 <?php  2/**  3  * Verification Signature  4  * @param $prestr need to sign the string  5  * @param $sign Signature result  6  * return signature result  7  */ 8 function rsaverify ($prestr, $sign) {&nbsp ; 9     $sign = Base64_decode ($sign);     $public _key= file_get_contents (' Rsa_public_key.pem '); One     $pkeyid = Openssl_get_publickey ($public _key);     if ($pkeyid{        $verify = openssl_verify ($prestr, $sign, $pkeyid); opens         Sl_free_key ($pkeyid);    }     if ($verify = = 1) {        return true;    }else{         return false; ?>    } Copy code note: 1. $PRESTR content is the same as MD5 (see Manual) 2. $sign is the sign parameter returned by the Alipay interface with Base64_decode decoded binary 3. Pay Bao gong for verification Key 4. This function returns a Boolean value that tells you directly whether the check is processed via the PHP version of the MD5 encryption method provided by the official     Alipay, but the Android and iOS request Alipay encryption methods can only be used with RSA encryption algorithm, At this point the server PHP can not verify the signature, so you need to make some changes to the demo.   1, modify alipay_notify.class.php file   verifynotify function 46th line   $isSign = $this->getsignveryfy ($_post, $_post ["sign"]);   changed to $isSign = $this->getsignveryfy ($_post, $_post["sign"], $_post["Sign_type"]);    Verifyreturn function line 83rd $isSign = $this->getsignveryfy ($_get, $_get["sign"]);  to   $isSign = $this->getsignveryfy ($_get , $_get["sign"], $_get["Sign_type"]);     GetsiGnveryfy function 116 line functions Getsignveryfy ($para _temp, $sign) {Change to function Getsignveryfy ($para _temp, $sign, $sign _type) {&NB Sp   GETSIGNVERYFY function 127 line switch (Strtoupper (Trim ($this->alipay_config[' Sign_type '))) {    case "MD5":         $isSgin = md5verify ($prestr, $sign, $this->alipay_config[' key '); Break     Default:         $isSgin = false; }  switch (strtoupper (Trim ($sign _type))) {    case "MD5":         $isSgin = Md5ver Ify ($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 <?php  2/*  3  * RSA  4  * Details: RSA Encryption & Nbsp;5  * Version: 3.3  6  * Date: 2014-02-20  7  * Description: &Nbsp;8  * The following code is only for the convenience of merchant test sample code, the merchant can according to their own website needs, according to technical documentation, not necessarily use the code.  9  * This code is only for learning and research Alipay interface use, but provides a reference. /**  * Signature String  */ * @param $prestr need to sign the string  * return signature result  */ IGN ($PRESTR) {    $public _key= file_get_contents (' Rsa_private_key.pem ');     $pkeyid = Openssl_ Get_privatekey ($public _key);     Openssl_sign ($prestr, $sign, $pkeyid);     Openssl_free_key ($pkeyid);     $sign = Base64_encode ($sign);     return $sign; /**  * Verify signature  * @param $prestr The string to be signed  * @param $sign signature result  * return signature result &nbs p;*/function Rsaverify ($prestr, $sign) {    $sign = Base64_decode ($sign);     $public _key= file_get_contents (' Rsa_public_key.pem ');     $pkeyid = Openssl_get_publickey ($public _key);     if ($pkeyid) {        $verify = Openssl_verIfy ($prestr, $sign, $pkeyid);         Openssl_free_key ($pkeyid); Notoginseng    }     if ($verify = = 1) {        return true;    }else{         return false;    }?> copy code The last thing to say is that the official manual to say is basically correct, but some places did not say very detailed, the development of the time must be more reference, is roughly the case, I wish you good luck.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.