Example of rsa Asymmetric Encryption Class Implemented by ThinkPHP
- 2021-10-13 06:58:23
- OfStack
In this paper, an example is given to describe the rsa asymmetric encryption class implemented by ThinkPHP. Share it for your reference, as follows:
The string encrypted by the public key is 1 straight change, but the content decrypted by the private key is still the same, which is used for encrypting data.
The string encrypted by the private key will not change, Even when exposed to the extranet, others can't see the content without the public key. Only the third party who gives the public key is allowed to decrypt and see the content. The actual effect is equivalent to the signature function. If you can get the unencrypted content, it shows that 1 must be the data of the trusting party, because there is his signature.
In fact, this asymmetric encryption technology can be used in single sign-on, with high security level, and the content obtained by decryption should be the data of the trusted party.
<?php
namespace Common\Org;
class RsaCrypt {
const CERPATH ='../Application/Runtime/Data/server.cer'; // Generate certificate path
const PFXPATH = '../Application/Runtime/Data/server.pfx'; // Key file path
const FILEDIR = '../Application/Runtime/Data/';
/**
* Generate public key and private key
*/
public static function generateCertKey()
{
$dn = array('countryName'=>'CN', 'stateOrProvinceName'=>'beijing', 'localityName'=>'beijing','organizationName'=>'clcw',
'organizationalUnitName'=>'clcw', 'commonName'=>'clcw', 'emailAddress'=>'service@clcw.com.cn');
$privkeypass = 'secret'; // Private key cryptography
$numberOfDays = 365; // Effective duration in days
// Generate a certificate
$privkey = openssl_pkey_new();
$csr = openssl_csr_new($dn, $privkey);
$sscert = openssl_csr_sign($csr, null, $privkey, $numberOfDays);
openssl_x509_export_to_file($sscert, self::CERPATH);
openssl_pkcs12_export_to_file($sscert, self::PFXPATH, $privkey, $privkeypass);
(file_exists(self::CERPATH)) or die(' Wrong file path for public key ');
(file_exists(self::PFXPATH)) or die(' Wrong file path for key ');
}
public static function verifyData($originData, $decryptData)
{
$cer_key = file_get_contents(self::$cerpath);
$cer = openssl_x509_read($cer_key);
$res = openssl_verify($originData, $decryptData, $cer);
var_dump($res);
}
/**
* Generate public key and private key files
* @param $appName string Application name
*/
public static function generateKey($appName='')
{
$result = ['status'=>0, 'msg'=>''];
if (!extension_loaded('openssl') ) {
$result['msg'] = 'php Need openssl Support ';
}
// Create a public key
$res = openssl_pkey_new();//array('private_key_bits'=>512) This 1 String parameters are not added, otherwise they can only be encrypted 54 A string of three lengths
// Extract private key
openssl_pkey_export($res, $privatekey);
// Generate public key
$public_key = openssl_pkey_get_details($res);
$publickey = $public_key['key'];
// $path = self::FILEDIR.$appName;
try{
// file_put_contents($path.'_public.pem', $publickey);
// file_put_contents($path.'_private.pem', $privatekey);
$result['status'] = 1;
$result['publickey'] = $publickey;
$result['privatekey'] = $privatekey;
}catch(\Exception $e) {
// throw new \Exception($e->getMessage());
$result['msg'] = $e->getMessage();
}
return $result;
}
/**
* Encrypt data with a private key
* @param $data string String to be encrypted ( It is best not to exceed 200 Characters )
* @param $appName string Application name
*/
public static function privateEncrypt($data, $appName)
{
$result = ['status'=>0, 'msg'=>''];
$privatekey = C($appName.'.PRIVATE_KEY');
$myinfo = 'In '.__METHOD__.',privatekey:'.$privatekey."\n";
file_put_contents('/tmp/shiyf.log', $myinfo, FILE_APPEND);
// Generate resource If the contents of the key file are corrupted, openssl_pkey_get_private Function returns false
$privatekey = openssl_pkey_get_private($privatekey);
if (empty($privatekey)) {
$result['msg'] = ' Key not available ';
}
$encryptData = '';
// Encryption with private key
if (openssl_private_encrypt($data, $encryptData, $privatekey)) {
$result['msg'] = base64_encode($encryptData);
$result['status'] = 1;
} else {
$result['msg'] = ' Encryption failed! ';
}
return $result;
}
/**
* Decrypt data with a public key
* @param $data string String to be decrypted ( It is best not to exceed 200 Characters )
* @param $appName string Application name
*/
public static function publicDecrypt($data, $appName)
{
$result = ['status'=>0, 'msg'=>''];
$data = base64_decode($data);
$publickey = C($appName.'.PUBLIC_KEY');
// Generate resource If the contents of the public key file are corrupted, openssl_pkey_get_public Function returns false
$publickey = openssl_pkey_get_public($publickey);
if (empty($publickey)) {
$result['msg'] = ' Public key unavailable ';
}
// Decrypt data
$decryptData = '';
if (openssl_public_decrypt($data, $decryptData, $publickey)) {
$result['msg'] = $decryptData;
$result['status'] = 1;
} else {
$result['msg'] = ' Decryption failed ';
}
return $result;
}
/**
* Encrypt data with a public key
* @param $data string String to be encrypted ( It is best not to exceed 200 Characters )
* @param $appName string Application name
*/
public static function publicEncrypt($data, $publickey)
{
$result = ['status'=>0, 'msg'=>''];
// Generate resource If the contents of the public key file are corrupted, openssl_pkey_get_private Function returns false
$publickey = openssl_pkey_get_public($publickey);
if (empty($publickey)) {
$result['msg'] = ' Public key unavailable ';
}
$encryptData = '';
// Encryption with private key
if (openssl_public_encrypt($data, $encryptData, $publickey)) {
$result['msg'] = base64_encode($encryptData);
$result['status'] = 1;
} else {
$result['msg'] = ' Encryption failed! ';
}
return $result;
}
/**
* Encrypt data with a private key
* @param $data string String to be decrypted ( It is best not to exceed 200 Characters )
* @param $appName string Application name
*/
public static function privateDecrypt($data, $appName)
{
$result = ['status'=>0, 'msg'=>''];
$data = base64_decode($data);
$privatekey = C($appName.'.PRIVATE_KEY');
// Generate resource If the contents of the private key file are corrupted, openssl_pkey_get_public Function returns false
$privatekey = openssl_pkey_get_private($privatekey);
if (empty($privatekey)) {
$result['msg'] = ' Private key unavailable ';
}
// Decrypt data
$decryptData = '';
if (openssl_private_decrypt($data, $decryptData, $privatekey)) {
$result['msg'] = $decryptData;
$result['status'] = 1;
} else {
$result['msg'] = ' Decryption failed ';
}
return $result;
}
}
PS: Friends who are interested in encryption and decryption can also refer to the online tools of this site:
Online RSA Encryption/Decryption Tool:
http://tools.ofstack.com/password/rsa_encode
Text online encryption and decryption tools (including AES, DES, RC4, etc.):
http://tools.ofstack.com/password/txt_encode
Online hash/hash algorithm encryption tool:
http://tools.ofstack.com/password/hash_encrypt
Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 Encryption Tool:
http://tools.ofstack.com/password/hash_md5_sha
Online sha1/sha224/sha256/sha384/sha512 Encryption Tool:
http://tools.ofstack.com/password/sha_encode
For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".
I hope this article is helpful to the PHP programming based on ThinkPHP framework.