SoFunction
Updated on 2025-03-04

SSL encryption decryption, verification and signature methods under PHP (very simple)

Super simple, relying on OpenSSL extension, so I won't talk much nonsense here, just present the code

sign:

function sign($data) {
 //Read the private key file $priKey = file_get_contents('key/rsa_private_key.pem');
 
 //Convert to openssl key, it must be a private key that has not been converted by pkcs8 $res = openssl_get_privatekey($priKey);
 
 //Calling the built-in signature method of openssl to generate the signature $sign openssl_sign($data, $sign, $res);
 
 //Release resources openssl_free_key($res);
 
 return $sign;
}

verify:

function verify($data, $sign) {
 //Read the 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 to verify the signature and return the bool value $result = (bool)openssl_verify($data, $sign, $res);
 
 //Release resources openssl_free_key($res);
 
 return $result;

Decryption

function decrypt($content) {
 
 //Read the merchant's private key $priKey = file_get_contents('key/rsa_private_key.pem');
 
 //Convert to openssl key, it must be a private key that has not been converted by pkcs8 $res = openssl_get_privatekey($priKey);
 
 //Declare clear literal string variable $result = '';
 
 //The loop is decrypted according to 128 bits for($i = 0; $i < strlen($content)/128; $i++ ) {
 $data = substr($content, $i * 128, 128);
  
 //Split the string fragment with length 128 and decrypt it through the private key, and return the plain text after parsing of $decrypt. openssl_private_decrypt($data, $decrypt, $res);
 
 //Plain text fragment splicing $result .= $decrypt;
 }
 
 //Release resources openssl_free_key($res);
 
 //Return to the plain text return $result;
}

I hope this article will be helpful for everyone to learn PHP programming.