找回密码
 注册
搜索
查看: 1968|回复: 0

PHP使用RSA的例子

[复制链接]
发表于 2014-12-17 15:15:42 | 显示全部楼层 |阅读模式
<?php
header("Content-Type: text/html; charset=utf-8");
//私钥
$private_key = '-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCpQ6CMgJe7NmXHpNPFcqdX1hsZQZH5j3WN2hRdfBTG5nQH8ifS
4+BVqifL0JjuffZdHJXqGQon4HD9i64cQ6Ps0kgbAMfNWsvhC+IJYAfH7hBRmB/d
1J4Bucr0o+diWp+7Vmp+QS9H5n6WxvSYglySFXvn5Z5FStWZGuoO3VgIwQIDAQAB
AoGAXvGRJ96lvZyIwNCi/TkPxwRRFPyjvgGLZfMywzFrkhoIccCSOAgceNDGG9w5
PGWpgJcdPD+pY67Qklf8ZNxIIQ/CYO+YB20dyio138jNLFTRmvUbzkK+9g1h0LF1
ksbK5sfTPLplK4lKbowDK9XiuSGJThOiN5qEiiWCNMlgowECQQDfZhWxVh7jzlyU
MuLvc8ZzgSdNJaH3upx8asFspvqXFpuj/GYaMuEwFfT4Mz9QTgT8zeaij/zpivTN
I3bEKeYRAkEAwfcjLb75RSCUKD1d84cUcQauZmyCRymu/C4/Whxr1AO0lIUc94cU
sgkdxqMnbJPca5+rQE9aDmf9cslUMj2HsQJAIh1cwq/8F52z1Y3PyfFMJOdcMRPG
ICaHLxi+YPE+40O4kNpCXU3XxZgUyLJKwOCpMlHfHoQOgzuNFqaLxHkBgQJAW6Rc
Zpy4QUTnOyvjW9AShGRXueTCmMTE/DkNjZGoEH+/rfxGd1zHFmbgPp2PXultVxwV
WUkkj3HqeXVN5n7TwQJAaySbpZjetKJjx33a/jbLY26OczTtAw5t4FK84x8ka29r
wEuqs5+e2eanroktyeiLi8j/difKHDSWdTD+TiJqoA==
-----END RSA PRIVATE KEY-----';
//公钥
$public_key = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpQ6CMgJe7NmXHpNPFcqdX1hsZ
QZH5j3WN2hRdfBTG5nQH8ifS4+BVqifL0JjuffZdHJXqGQon4HD9i64cQ6Ps0kgb
AMfNWsvhC+IJYAfH7hBRmB/d1J4Bucr0o+diWp+7Vmp+QS9H5n6WxvSYglySFXvn
5Z5FStWZGuoO3VgIwQIDAQAB
-----END PUBLIC KEY-----';

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

$data = "{from:jinhua,to:rayo,dongid:dasdd,dongcode:hajshh,type:4,posttime:2014-08-21}";//原始数据,明文
$encrypted = "";
$decrypted = "";

echo "原始数据:",$data,"<BR>";

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

echo "公钥解密:<br>";
openssl_public_decrypt(base64_decode($encrypted),$decrypted,$pu_key);//私钥加密的内容通过公钥可用解密出来
echo $decrypted,"<br>";

echo "公钥加密:<br>";
openssl_public_encrypt($data,$encrypted,$pu_key);//公钥加密
$encrypted = base64_encode($encrypted);
echo $encrypted,"<br>";

echo "私钥解密:<br>";
openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key);//私钥解密
echo $decrypted,"<br>";
?>

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|宁德市腾云网络科技有限公司 ( 闽ICP备2022007940号-5|闽公网安备 35092202000206号 )

GMT+8, 2025-5-4 22:07 , Processed in 0.014974 second(s), 15 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表