RSA key convert to PEM file

2019-02-24 13:13发布

问题:

How can I convert this RSA public key: 109120132967399429278860960508995541528237502902798129123468757937266291492576446330739696001110 6039072308886100726558188253585034290 57592827629436413108566029093628 2126359538366865626758497206207862794310902180176810615217550567108238764764442605581471797071 19674283982419152118103759076030616683978566631413

to *.pem file?

回答1:

A "pem" file is not really a format, and different kinds of objects may be be stored in things called "pem" files. Most often these files contain either a base64-encoded X509 certificate or else a base64-encoded private key object.

Assuming you want an X509 certificate, you should next realize that a certificate consists of many fields, only one of which is the public key. So would need to decide on the values of the other fields. Finally, a certificate must be signed, with a private key.

PS. An RSA public key consists of a modulus and a public exponent. What is your public exponent?



回答2:

If your hex string is just a simple convert from base64 to hex. Then you can reverse it. Here is the script I did (in PHP) to solve my case:

<?php

$list = array_slice($argv, 1);

foreach ($list as $file) {
    $hex = str_replace("\n", "", file_get_contents($file));
    $pem = str_replace(".hex", ".pem", $file);
    $b64 = base64_encode(hex2bin($hex));
    $fd = fopen($pem, 'w');
    fprintf($fd, "-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY----\n", implode("\n", str_split($b64, 64)));
    fclose($fd);
}

Given a list of .hex files, it convert back to ".pem". You can run it like this:

php script.php *.hex


回答3:

I would use OpenSSL. Assuming that you have the key in DER format, you can use this command to convert from DER to PEM.

openssl x509 -inform der -in input.der -out output.pem

If you are not sure whether you have the correctly formatted DER (ASN.1) encoded key, try this tool to parse your input file.



回答4:

use putty programs, PuTTYgen does this conversion