English | 简体中文 | 繁體中文
查询

openssl_pkey_export()函数—用法及示例

「 将一个密钥导出到一个字符串中 」


函数名称: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' 中。

补充纠错
热门PHP函数
分享链接