本文實例講述了php基於openssl的rsa加密解密。分享給大家參考,具體如下:
"D:/phpserver/Lighttpd/openssl.cnf", //'config' =>'D:/phpStudy/Lighttpd/OpenSSL.cnf', 'private_key_bits' => 1024, // Size of Key. 'private_key_type' => OPENSSL_KEYTYPE_RSA ); //$res = openssl_pkey_new(); $res = openssl_pkey_new($config); // Get private key // openssl_pkey_export($res, $privkey, "PassPhrase number 1" ); openssl_pkey_export($res, $privkey); var_dump($privkey); // Get public key $pubkey=openssl_pkey_get_details($res); // echo "------------>
"; // print_r($pubkey["rsa"]); // $bin_str=$pubkey["rsa"]["n"]; // print_r($bin_str); // echo "
"; // //echo $bin_hex_str = pack("H*" , bin2hex($bin_str)); // echo $bin_hex_str = bin2hex($bin_str); // echo "
------------<
"; $pubkey=$pubkey["key"]; // var_dump($privkey); // var_dump($pubkey); echo $privkey."
"; echo $pubkey."
"; ?>
----------------------
"; $data = "woshizhu";//原始数据 $encrypted = ""; $decrypted = ""; echo "source data:",$data,"
"; echo "private key encrypt:\n"; openssl_private_encrypt($data,$encrypted,$pi_key);//私钥加密 $encrypted = base64_encode($encrypted);//加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的 echo "
----------私钥加密------------
"; echo $encrypted,"
"; echo "
----------私钥加密------------
"; echo "public key decrypt:\n"; $decrypted=""; openssl_public_decrypt(base64_decode($encrypted),$decrypted,$pu_key);//私钥加密的内容通过公钥可用解密出来 echo $decrypted,"\n"; echo "---------------------------------------\n"; echo "public key encrypt:\n"; openssl_public_encrypt($data,$encrypted,$pu_key);//公钥加密 $encrypted = base64_encode($encrypted); echo $encrypted,"\n"; $decrypted=""; //$encrypted="JBeapcp9iWWYJYElgqtrZxfxM4wVkCaSn/oJZ7NjfR23o76fdbxEXpf+PGWACw3PeTdObwL4108wR3ihKmy2iYkIExGjBYyvx2w9aHies8ZsOIP3LjiMHYTm93Rr8Sc5XxHWQc3Dhbq16JWHYZ2d+RrOpHd4x84GF3JXwivrGO4="; echo "private key decrypt:\n"; openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key);//私钥解密 echo "--->:".$decrypted,"\n"; ?>
希望本文所述對大家PHP程式設計有所幫助。
更多php基於openssl的rsa加密解密範例相關文章請關注PHP中文網!