rsa.php,Rsa.php - 树梢上的蝉的个人空间 - OSCHINA - 中文开源技术交流社区

namespace app\common;

class Rsa

{

private $private_key;

private $public_key;

public function __construct()

{

$this->private_key = file_get_contents("./rsa/rsa_private_key.pem");

$this->public_key = file_get_contents("./rsa/rsa_public_key.pem");

}

public function demo()

{

$pi_key=openssl_pkey_get_private($this->private_key);//这个函数可用来判断私钥是否是可用的,可用返回资源id Resource id

$pu_key=openssl_pkey_get_public($this->public_key);//这个函数可用来判断公钥是否是可用的

print_r($pi_key);echo "\n"; echo "
";

print_r($pu_key);echo "\n"; echo "
";

echo "


";

$data='php ras加密算法';

$encrypted = "";

$decrypted = "";

echo "加密的源数据:".$data."\n"; echo "
";

echo "private key encrypt:\n"; echo "
";

openssl_private_encrypt($data,$encrypted,$pi_key,OPENSSL_PKCS1_PADDING);//私钥加密

$encrypted = base64_encode($encrypted);//加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的

echo '私钥加密后:'.$encrypted."\n"; echo "
";echo "
";

echo "public key decrypt:\n"; echo "
";

openssl_public_decrypt(base64_decode($encrypted),$decrypted,$pu_key,OPENSSL_PKCS1_PADDING);//私钥加密的内容通过公钥可用解密出来

echo '公钥解密后:'.$decrypted."\n"; echo "
";

echo "


";

echo "public key encrypt:\n"; echo "
";

openssl_public_encrypt($data,$encrypted,$pu_key,OPENSSL_PKCS1_PADDING);//公钥加密

$encrypted = base64_encode($encrypted);

echo $encrypted,"\n"; echo "
";

echo "private key decrypt:\n"; echo "
";

openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key,OPENSSL_PKCS1_PADDING);//私钥解密

echo $decrypted,"\n"; echo "
";

}

/**

* 公钥加密

* @param unknown $data

* @param unknown $padding

*/

public function encrypt($data, $padding=OPENSSL_PKCS1_PADDING)

{

openssl_public_encrypt($data,$encrypted,$this->public_key, $padding);//公钥加密

return base64_encode($encrypted);;

}

/**

* 私钥解密

* @param unknown $encrypted

* @param unknown $padding

*/

public function decrypt($encrypted, $padding=OPENSSL_PKCS1_PADDING)

{

openssl_private_decrypt(base64_decode($encrypted),$decrypted,$this->private_key,$padding);//私钥解密

return $decrypted;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值