首页 > 代码库 > RSA加密解密(PHP Demo)
RSA加密解密(PHP Demo)
1 $private_key = ‘-----BEGIN RSA PRIVATE KEY----- 2 MIICXQIBAAKBgQDpoODVtnSztGyb//p+g/Ob36jb3jzWzS2qovOjpY/rrTjwlVcQ 3 pB2m1nZDQNpTFsG8ZBl7uPw3M81lr7NRRn6tY7Om8tbOOsRgY6u0xwbgdRStFFvw 4 PzZ1HehiQ6WB8za8cucCyvuqmBRp7HOjO4Aa9t0rIvZ/hoWMeSvjnAVbMwIDAQAB 5 AoGBAOEHsaiIDs6NKdP08r1rsXjhLI9i92zawnLKdCybKw4RknfBENSZj2oExnKv 6 A9vmXoNsU1NlcaJmRh/85ZaSdS4L+Zx8iz18uwXAjCPpfMd7nG4FD55713Lszhua 7 DQIxK06w2mI0ytwEf4cqQmct2/BWchBXZIlz9O0Q70CF2brpAkEA/3NtHrQNxbF0 8 KRvrrTw4c9Y76PyeESEmKuF8ZKQu6v1qSb/V3aZsiGPTH+vUf0oAmoJoGx1AtRuk 9 DAe9uQ5efQJBAOohcXTh7vgm5ujlyJEi85jGp2BnHxmNAHN6n1q44Hs1wbvICujH10 SEaHhVt6hSf7/NXnGOtJXve0JIt5glvCX28CQCa1jASKDkg10r9j/ruak4diIGP211 29EGr+zxjFMH2iA71H5mdncHAA1O6zA8IVBEm4DOYA4zyZloHdzA04wWVFUCQQDY12 9+cJVvq6smpYN+E3RrmRwb6IYuf6KKXbXi5gx2UYKQgA+e/KKis7WQlnbdIJ7MYw13 f7mjCVpdmG4pZpA8cpM3AkAFRUXYKlxLusKBRDZSDCyCUzP/Y3ql/qWXOqcA5Brj14 pj+cofEWd/jZqD3drFjDGvccFmTfEAVmXWxCnJAZU2cW15 -----END RSA PRIVATE KEY-----‘;16 17 $public_key = ‘-----BEGIN PUBLIC KEY-----18 MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDpoODVtnSztGyb//p+g/Ob36jb19 3jzWzS2qovOjpY/rrTjwlVcQpB2m1nZDQNpTFsG8ZBl7uPw3M81lr7NRRn6tY7Om20 8tbOOsRgY6u0xwbgdRStFFvwPzZ1HehiQ6WB8za8cucCyvuqmBRp7HOjO4Aa9t0r21 IvZ/hoWMeSvjnAVbMwIDAQAB22 -----END PUBLIC KEY-----‘;23 24 //echo $private_key;25 $pi_key = openssl_pkey_get_private($private_key);//这个函数可用来判断私钥是否是可用的,可用返回资源id Resource id26 $pu_key = openssl_pkey_get_public($public_key);//这个函数可用来判断公钥是否是可用的27 print_r($pi_key);echo "\n";28 print_r($pu_key);echo "\n";29 30 31 $data = "123";//原始数据32 $encrypted = "";33 $decrypted = "";34 35 echo "source data:",$data,"\n";36 37 echo "private key encrypt:\n";38 39 openssl_private_encrypt($data,$encrypted,$pi_key);//私钥加密40 $encrypted = base64_encode($encrypted);//加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的41 echo $encrypted,"\n";42 43 echo "public key decrypt:\n";44 45 openssl_public_decrypt(base64_decode($encrypted),$decrypted,$pu_key);//私钥加密的内容通过公钥可用解密出来46 echo $decrypted,"\n";47 48 echo "---------------------------------------\n";49 echo "public key encrypt:\n";50 51 openssl_public_encrypt($data,$encrypted,$pu_key);//公钥加密52 $encrypted = base64_encode($encrypted);53 echo $encrypted,"\n";54 55 echo "private key decrypt:\n";56 openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key);//私钥解密57 echo $decrypted,"\n";
密钥采用openssl工具生成,命令:
1. 生成 rsa 私钥
openssl genrsa -out rsaprivatekey.pem 1024
2. 生成对应的公钥
openssl rsa -in rsaprivatekey.pem -pubout -out rsapublickey.pem
3. 将 RSA 私钥转换成 PKCS8 格式,
openssl pkcs8 -topk8 -inform PEM -in rsaprivatekey.pem -outform PEM -nocrypt -out
rsaprivatepkcs8.pem
RSA加密解密(PHP Demo)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。