php openssl对称加密

公钥,私钥文件需要在Linux下生成!

相关命令:

私钥:

openssl genrsa -out rsa_private_key.pem 1024  

公钥:

openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem  

代码如下:

<?php

/**
 * @uses openssl加密解密
 * @author jhl
 *
 */
class OpensslAuthcode {
	
	//公钥文件地址
	private $certPublicUrl;
	
	//私钥文件地址
	private  $certPrivateUrl;
	
	public function __construct()
	{
		$this->certPublicUrl = __DIR__ . "/opensslkey/cert_public.key";
		$this->certPrivateUrl = __DIR__ . "/opensslkey/cert_private.pem";
	}
	
	/**
	 *
	 * @uses 生成证书文件
	 * @author jhl
	 * @return file
	 */
	public function exportOpenSSLFile() {
		$config = [
				'digest_alg' => 'sha512',
				'private_key_bits' => 4096,
				'private_key_type' => OPENSSL_KEYTYPE_RSA 
		];
		$res = openssl_pkey_new ( $config );
		if ($res == false) {
			return false;
		}
		openssl_pkey_export ( $res, $private_key );
		$public_key = openssl_pkey_get_details ( $res );
		$public_key = $public_key ['key'];
		file_put_contents ( $this->certPublicUrl, $public_key );
		file_put_contents ( $this->certPrivateUrl, $private_key );
		openssl_free_key ( $res );
	}
	
	/**
	 *
	 * @uses 加密
	 * @author jhl
	 * @param string $string        	
	 * @return string
	 */
	public function encrypt($string) {
		$sslPublic = self::getPublicKey();
		$sslPrivate = self::getPrivateKey();
		$privateKey = openssl_pkey_get_private ( $sslPrivate );
		$publicKey = openssl_pkey_get_public ( $sslPublic );
		if (false == ($privateKey || $publicKey)) {
			return 'certificate error!!';
		}
		openssl_public_encrypt ( $string, $data, $publicKey );
		$data = base64_encode ( $data );
		return $data;
	}
	
	/**
	 *
	 * @uses 解密
	 * @author jhl
	 * @param string $string        	
	 * @return string
	 */
	public function decrypt($string) {
		$sslPublic = self::getPublicKey();
		$sslPrivate = self::getPrivateKey();
		$privateKey = openssl_pkey_get_private ( $sslPrivate );
		$publicKey = openssl_pkey_get_public ( $sslPublic );
		if (false == ($privateKey || $publicKey)) {
			return 'certificate error!!';
		}
		openssl_private_decrypt ( base64_decode ( $string ), $data, $privateKey );
		return $data;
	}
	
	/**
	 *
	 * @uses 获取公钥
	 * @author jhl
	 * @param string $string
	 * @return string
	 */
	private function getPublicKey()
	{
		static $sslPublicKey;
		if (!$sslPublicKey) {
			$sslPublicKey = file_get_contents ( $this->certPublicUrl );
		}
		return $sslPublicKey;
	}
	
	/**
	 *
	 * @uses 获取私钥
	 * @author jhl
	 * @param string $string        	
	 * @return string
	 */
	private function getPrivateKey()
	{
		static $sslPrivateKey;
		if (!$sslPrivateKey) {
			$sslPrivateKey = file_get_contents ( $this->certPrivateUrl );
		}
		return $sslPrivateKey;
	}
	
}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值