温馨提示×

openssl_pkey_new在PHP中的最佳实践

PHP
小樊
83
2024-09-05 02:11:06
栏目: 云计算

在 PHP 中,openssl_pkey_new() 函数用于生成新的公钥和私钥对

  1. 使用 openssl_pkey_new() 创建密钥对:
$config = array(
    "digest_alg" => "sha512",
    "private_key_bits" => 4096,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

$res = openssl_pkey_new($config);
if ($res === false) {
    throw new Exception("Failed to generate key pair");
}
  1. 提取并存储公钥和私钥:
// 获取私钥
openssl_pkey_export($res, $privateKey);

// 获取公钥
$publicKey = openssl_pkey_get_details($res);
$publicKey = $publicKey["key"];

// 将公钥和私钥保存到文件中
file_put_contents("private_key.pem", $privateKey);
file_put_contents("public_key.pem", $publicKey);
  1. 使用公钥加密数据,私钥解密数据:
// 加载公钥和私钥
$publicKey = openssl_pkey_get_public("file://public_key.pem");
$privateKey = openssl_pkey_get_private("file://private_key.pem");

// 原始数据
$data = "Hello, world!";

// 使用公钥加密数据
$encryptedData = '';
openssl_public_encrypt($data, $encryptedData, $publicKey);

// 使用私钥解密数据
$decryptedData = '';
openssl_private_decrypt($encryptedData, $decryptedData, $privateKey);

echo "Original data: " . $data . PHP_EOL;
echo "Decrypted data: " . $decryptedData . PHP_EOL;
  1. 使用私钥签名数据,公钥验证签名:
// 原始数据
$data = "Hello, world!";

// 使用私钥签名数据
$signature = '';
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA512);

// 使用公钥验证签名
$isValid = openssl_verify($data, $signature, $publicKey, OPENSSL_ALGO_SHA512);

if ($isValid) {
    echo "Signature is valid." . PHP_EOL;
} else {
    echo "Signature is invalid." . PHP_EOL;
}

这些示例展示了如何在 PHP 中使用 openssl_pkey_new() 函数生成密钥对,以及如何使用公钥和私钥进行加密、解密、签名和验证操作。请确保在生产环境中使用更安全的密钥长度和加密算法。

0