函式名稱:openssl_pkey_export()
函式描述:openssl_pkey_export() 函式用於將一個金鑰匯出到一個字串中。
適用版本:該函式在 PHP 4.2.0 及以上版本可用。
用法:
bool openssl_pkey_export ( mixed $key , string &$out [, string $passphrase [, array $configargs ]] )
引數:
$key
:必需,要匯出的金鑰,可以是 OpenSSL 公鑰、私鑰或金鑰對。$out
:必需,儲存匯出的金鑰的字串變數。$passphrase
:可選,用於保護私鑰的可選密碼短語。$configargs
:可選,用於配置 OpenSSL 金鑰的可選引數。
返回值:
- 如果匯出成功,則返回 true,否則返回 false。
示例:
// 生成一個新的 RSA 金鑰對
$config = array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$privateKey = openssl_pkey_new($config);
openssl_pkey_export($privateKey, $privateKeyString);
// 儲存私鑰到檔案
file_put_contents('private.key', $privateKeyString);
// 匯出公鑰
$publicKey = openssl_pkey_get_details($privateKey)['key'];
file_put_contents('public.key', $publicKey);
在上面的示例中,我們使用 openssl_pkey_new()
生成一個新的 RSA 金鑰對。然後,我們使用 openssl_pkey_export()
函式將私鑰匯出到字串變數 $privateKeyString
中。最後,我們將私鑰儲存到檔案 'private.key' 中,並使用 openssl_pkey_get_details()
函式獲取公鑰,並儲存到檔案 'public.key' 中。