How to generate PKCS#1 RSA keys in PEM Format?

亡梦爱人 提交于 2019-12-03 13:51:00

问题


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.


回答1:


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



回答2:


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-----


来源:https://stackoverflow.com/questions/10783366/how-to-generate-pkcs1-rsa-keys-in-pem-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!