PHP under SSL encryption decryption, verification, signature method (very simple) _php tips

Source: Internet
Author: User
Tags decrypt openssl php programming

Super simple, dependent on the OpenSSL extension, here is no more nonsense, directly to the code

Signature:

function sign ($data) {
 //Read private key file
 $priKey = file_get_contents (' Key/rsa_private_key.pem ');
 
 Conversion to OpenSSL key must be a private key without pkcs8 conversion
 $res = Openssl_get_privatekey ($priKey);
 
 Call the OpenSSL built-in signature method to generate the signature $sign
 openssl_sign ($data, $sign, $res);
 
 Release of resources
 Openssl_free_key ($res);
 
 return $sign;
}

Verify:

function Verify ($data, $sign) {
 //Read Alipay public key file
 $pubKey = file_get_contents (' Key/alipay_public_key.pem ');
 
 Convert to OpenSSL format key
 $res = Openssl_get_publickey ($pubKey);
 
 Call OpenSSL built-in method verification, return bool value
 $result = (bool) openssl_verify ($data, $sign, $res);
  
 Release of resources
 Openssl_free_key ($res);
 
 return $result;

Decrypt

function Decrypt ($content) {
 
 //Read merchant private key
 $priKey = file_get_contents (' Key/rsa_private_key.pem ');
  
 Conversion to OpenSSL key must be a private key without pkcs8 conversion
 $res = Openssl_get_privatekey ($priKey);
 
 Declares the plaintext string variable
 $result = ';
 
 Loops are decrypted in 128-bit for
 ($i = 0; $i < strlen ($content)/128 $i + +) {
  $data = substr ($content, $i * 128, 128);
   
 The split length 128 string fragment is decrypted by the private key and returns the plaintext
  Openssl_private_decrypt ($data, $decrypt, $res) after $decrypt parsing;
 
 Clear-Text fragment stitching
  $result. = $decrypt;
 }
 
 Release of resources
 Openssl_free_key ($res);
 
 Returns the plaintext return
 $result;
}

I hope this article will help you learn about PHP programming.

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.