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

用户名

目前,我有一些有效的php代码来生成私有/公共密钥对并将它们存储在两个变量中。这些变量是字符串,其中一个变量包含私钥,另一个变量包含公钥。我研究了堆栈溢出,还发现了一些代码,可将pem编码的密钥字符串转换为der编码的密钥字符串。但是,我不知道如何将公钥字符串转换为pem格式以将其转换为der。请不要因为我最终不需要将字符串转换为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()的API时openssl_pkey_get_public()即使密钥对不是证书(由的方法描述推测openssl_pkey_get_public()也应尝试使用此方法

openssl_pkey_new()生成一个新的私钥和公钥对。可以使用来获取密钥的公共部分openssl_pkey_get_public()


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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章