函式名稱:openssl_dh_compute_key()
函式描述:該函式使用Diffie-Hellman金鑰交換協議計算共享金鑰。
引數:
- $pub_key: 公鑰字串。
- $dh_key: Diffie-Hellman金鑰資源。
返回值:成功時返回共享金鑰的字串,失敗時返回false。
適用版本:PHP 5 >= 5.3.0, PHP 7
示例:
// 建立Diffie-Hellman金鑰對
$dh_config = [
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_DH,
];
$dh_res = openssl_pkey_new($dh_config);
openssl_pkey_export($dh_res, $dh_priv_key);
$dh_details = openssl_pkey_get_details($dh_res);
$pub_key = $dh_details['dh']['pub_key'];
// 計算共享金鑰
$shared_key = openssl_dh_compute_key($pub_key, $dh_res);
echo "共享金鑰: " . bin2hex($shared_key) . "\n";
在上面的示例中,我們首先使用openssl_pkey_new()函式建立了一個Diffie-Hellman金鑰對,並使用openssl_pkey_export()匯出私鑰。然後,我們使用openssl_pkey_get_details()函式獲取公鑰。接下來,我們使用openssl_dh_compute_key()函式計算共享金鑰。最後,我們將共享金鑰以十六進位制字串的形式列印出來。
請注意,為了執行此示例,您的PHP版本必須為5.3.0或更高,並且必須啟用OpenSSL擴充套件。