使用PHP生成公钥/私钥对,并将公钥导出为.der编码的字符串

时间:2015-06-20 16:28:57

标签: php openssl cryptography

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

我的代码如下:

$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

提前致谢!

1 个答案:

答案 0 :(得分:4)

阅读openssl_pkey_new()的API,您应该使用openssl_pkey_get_public()尝试此操作,即使密钥对不是证书(由openssl_pkey_get_public()的方法说明推测):< / p>

  

openssl_pkey_new()生成新的私钥和公钥对。可以使用openssl_pkey_get_public()获取密钥的公共组件。

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

相关问题