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 DAe9uQ5efQJBAOohcXTh7vgm5ujlyJEi85jGp2BnHxmNAHN6n1q44Hs1wbvICujH 10 SEaHhVt6hSf7/NXnGOtJXve0JIt5glvCX28CQCa1jASKDkg10r9j/ruak4diIGP2 11 29EGr+zxjFMH2iA71H5mdncHAA1O6zA8IVBEm4DOYA4zyZloHdzA04wWVFUCQQDY 12 9+cJVvq6smpYN+E3RrmRwb6IYuf6KKXbXi5gx2UYKQgA+e/KKis7WQlnbdIJ7MYw 13 f7mjCVpdmG4pZpA8cpM3AkAFRUXYKlxLusKBRDZSDCyCUzP/Y3ql/qWXOqcA5Brj 14 pj+cofEWd/jZqD3drFjDGvccFmTfEAVmXWxCnJAZU2cW 15 -----END RSA PRIVATE KEY-----‘; 16 17 $public_key = ‘-----BEGIN PUBLIC KEY----- 18 MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDpoODVtnSztGyb//p+g/Ob36jb 19 3jzWzS2qovOjpY/rrTjwlVcQpB2m1nZDQNpTFsG8ZBl7uPw3M81lr7NRRn6tY7Om 20 8tbOOsRgY6u0xwbgdRStFFvwPzZ1HehiQ6WB8za8cucCyvuqmBRp7HOjO4Aa9t0r 21 IvZ/hoWMeSvjnAVbMwIDAQAB 22 -----END PUBLIC KEY-----‘; 23 24 //echo $private_key; 25 $pi_key = openssl_pkey_get_private($private_key);//这个函数可用来判断私钥是否是可用的,可用返回资源id Resource id 26 $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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。