在php 5.2版本中,openssl這個擴展的應用非常廣泛,它提供了安全的加密通信協議和數據加密處理功能,也可以用于創建和驗證數字證書,具有廣泛用途和靈活性。比如:
//從字符串中生成一對公私鑰 $config = array( "private_key_bits" =>1024, "private_key_type" =>OPENSSL_KEYTYPE_RSA, ); $res = openssl_pkey_new($config); openssl_pkey_export($res, $privkey); $pubkey = openssl_pkey_get_details($res); $pubkey = $pubkey["key"]; //進行數據的加密和解密等操作 $data = "hello openssl"; $encrypted = ''; $decrypted = ''; //加密 openssl_private_encrypt($data, $encrypted, $privkey, OPENSSL_PKCS1_PADDING); //解密 openssl_public_decrypt($encrypted, $decrypted, $pubkey, OPENSSL_PKCS1_PADDING); echo $decrypted; // "hello openssl"
openssl擴展提供了很多簡單易用的加密和解密函數,比如使用openssl_encrypt函數可以方便地對數據進行加密,示例代碼如下:
$data = "hello openssl"; $password = "password"; $method = "aes-128-cbc"; $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method)); $encrypted = openssl_encrypt($data, $method, $password, 0, $iv); $decrypted = openssl_decrypt($encrypted, $method, $password, 0, $iv); echo $decrypted; //"hello openssl"
在網站開發中,我們有時會使用到ssl證書,用于實現https加密傳輸和驗證網站身份等操作。使用openssl擴展中的函數可以快速創建和驗證數字證書,比如:
//生成自簽名證書 $dn = array( "countryName" =>"CN", "stateOrProvinceName" =>"Beijing", "localityName" =>"Haidian", "organizationName" =>"PHP", "commonName" =>"localhost", ); $privkey = openssl_pkey_new(); $cert = openssl_csr_new($dn, $privkey); $cert = openssl_csr_sign($cert, null, $privkey, 365); openssl_x509_export($cert, $certout); //驗證數字證書是否合法 $x509 = openssl_x509_read($certout); $cinfo = openssl_x509_parse($x509); if ($cinfo) { echo "證書信息\n"; echo "=================================\n"; echo "公共名稱: " . $cinfo["subject"]["CN"] . "\n"; echo "頒發者: " . $cinfo["issuer"]["CN"] . "\n"; echo "有效期開始時間: " . date("Y-m-d H:i:s", $cinfo["validFrom_time_t"]) . "\n"; echo "有效期截止時間: " . date("Y-m-d H:i:s", $cinfo["validTo_time_t"]) . "\n"; echo "=================================\n"; }
除了以上應用,openssl擴展還可以用于數字簽名、哈希處理、隨機數生成等操作,非常方便實用。
上一篇php 5.2 nts
下一篇ajax 填充table