简体   繁体   中英

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

Currently I have some working php code to generate a private/public keypair and store them in two variables. These variables are strings, with one variable containing the private key, and the other containing the public key. I researched on stack overflow and I also found some code to convert a pem encoded key string to a der encoded key string. However, I don't know how to convert the public key string to pem format in order to convert it to der. Please not that I don't need to ultimately convert the sting to pem, I just need the der encoded string.

My code is below:

$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

Thanks in advance!

Reading the API of openssl_pkey_new() you should try this with openssl_pkey_get_public() even if the key pair isn't a certificate (which is speculated by the method description of 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() .


You don't have a certificate, so the PEM to DER will likely fail. The base 64 decoding is correct, but make sure you got the right header, footer and structure. You should amend it to comply to the representation of the public key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM