mic-kul
mic-kul

Reputation: 1009

RSA key convert to PEM file

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

to *.pem file?

Upvotes: 3

Views: 20274

Answers (5)

Rega
Rega

Reputation: 880

First of all President James K. Polk is right. A complete RSA Key is formed by a modulus and a public exponent. In Java, the interface RSAPublicKey from the package java.security.interfaces can hold well-formed RSA Keys. Assuming you have such object, the process of converting to a PEM format would involve encoding it, as follows:

String pemFormatKey = Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded());

Upvotes: 0

weilin8
weilin8

Reputation: 2985

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.

Upvotes: 0

President James K. Polk
President James K. Polk

Reputation: 42009

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?

Upvotes: 7

Diogo Melo
Diogo Melo

Reputation: 2213

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

Upvotes: 1

mpapis
mpapis

Reputation: 53178

use putty programs, PuTTYgen does this conversion

Upvotes: -2

Related Questions