使用 PHP 生成 public/private 密钥对并将 public 密钥导出为 .der 编码字符串

Use PHP to generate a public/private key pair and export public key as a .der encoded string

目前我有一些可用的 php 代码来生成 private/public 密钥对并将它们存储在两个变量中。这些变量是字符串,一个变量包含私钥,另一个变量包含 public 密钥。我研究了堆栈溢出,还发现了一些将 pem 编码的密钥字符串转换为 der 编码的密钥字符串的代码。但是,我不知道如何将 public 密钥字符串转换为 pem 格式,以便将其转换为 der。请注意,我不需要最终将 sting 转换为 pem,我只需要 der 编码的字符串。

我的代码如下:

$userKey = $_POST["key"];

$config = array(
    "digest_alg" => "sha512",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

function encryptData($value){
   $key = $userKey;
   $text = $value;
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
   return $crypttext;
}

// Create the keypair
$res = openssl_pkey_new($config);

// Get private key
openssl_pkey_export($res, $privKey);

// Get public key
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];

function pem2der($pem_data) {
   $begin = "CERTIFICATE-----";
   $end   = "-----END";
   $pem_data = substr($pem_data, strpos($pem_data, $begin)+strlen($begin));    
   $pem_data = substr($pem_data, 0, strpos($pem_data, $end));
   $der = base64_decode($pem_data);
   return $der;
}

$der = pem2der($pubKey);

//Send der data to client here

提前致谢!

读取 openssl_pkey_new()you should try this with openssl_pkey_get_public() 的 API 即使密钥对不是证书(由 openssl_pkey_get_public() 的方法描述推测):

openssl_pkey_new() generates a new private and public key pair. The public component of the key can be obtained using openssl_pkey_get_public().


您没有证书,因此 PEM 到 DER 很可能会失败。 base 64 解码是正确的,但要确保你有正确的页眉、页脚和结构。您应该修改它以符合 public 键的表示。