8
votes

Sorry for my english and honestly I have a very little understanding on this so please bear with me.

I am developing a java application that sends a signed request to a Server. To do so, I have to generate a PKCS#1 RSA key pair in PEM format for signing and verification. I've tried using OpenSSL v.1.0.1. but the public key generated is a X.509 PEM.

Here's the openssl command I used to generate the keys:

Private Key:

openssl genrsa -out name_of_private_key.pem 1024

Public Key

openssl rsa -in name_of_private_key.pem -pub out > name_of_public_key.pem

I've gone through this thread also and I found an open source JAVA library BouncyCastle: Generating RSA keys in PKCS#1 format in Java

But it says that BouncyCastle is only for PKCS#1 padding not encoding.

Preferably, I'm looking for ways to generate it using JAVA or any third parties if no other option is available.

3
Found an answer here hope this helpsJohne Altamera
Please post the answer so that it can help others.doptimusprime

3 Answers

14
votes

OPENSSL by default generate Private Key in PKCS#1 format it's as follows

-----BEGIN RSA PRIVATE KEY----- 
...
-----END RSA PRIVATE KEY-----

You can convert Private Key to PKCS#8 format and this is as follows

-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----

SSL Always export Public Key in X.509 format it's as follows

-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----

I use this bat script for generate RSA keypair.

@ECHO OFF
SET mypath=%~dp0
cd %mypath:~0,-1%

ECHO === GENERATE PRIVATE KEY --- Format: PKCS#1 --- File: private.txt===
openssl genrsa -f4 -out private.txt 4096 

ECHO === GENERATE PRIVATE KEY --- Format: PKCS#8 --- File: private8.txt===
openssl pkcs8 -topk8 -inform pem -in private.txt -outform PEM -nocrypt -out private8.txt

ECHO === GENERATE PUBLIC KEY --- Format: X.509 --- File: public.txt===
openssl rsa -in private.txt -outform PEM -pubout -out public.txt
PAUSE
7
votes

Although the OpenSSL library supports PKCS#1 encoding, the command line version of OpenSSL will only output RSA Public keys in x.509 format. Unfortunately it seems you are left with no option than to write some code that uses the OpenSSL library to output keys in PKCS#1 format.

For reference, a PKCS#1 key uses these headers/footers:

-----BEGIN RSA PUBLIC KEY----- 
...
-----END RSA PUBLIC KEY-----

Whereas a x.509 key uses these headers/footers:

-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
0
votes

You can force OpenSSH to generate keys in old PEM/PKCS#1 format:
ssh-keygen -t rsa -b 4096 -o -a 100 -f id_rsa -m PEM < /dev/null