Read Rsa Private Key of Format Pkcs1 in Java

Read RSA private key of format PKCS1 in JAVA

Java does not come with out-of-the-box support for PKCS1 keys. You can however use Bouncycastle

PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
Object object = pemParser.readObject();
KeyPair kp = converter.getKeyPair((PEMKeyPair) object);
PrivateKey privateKey = kp.getPrivate();

Getting RSA public key from PKCS1 key

You can use BouncyCastle library to achieve this. Your key is in PEM fromat. To read it you can use PEMParser :

private static PublicKey readPublicKey(String path) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
PEMParser pemParser = new PEMParser(new FileReader(path));
Object object = pemParser.readObject();
SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) object;

RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(subjectPublicKeyInfo);

RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
KeyFactory kf = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
return kf.generatePublic(rsaSpec);
}

And then to encrypt with this key :

PublicKey publicKey = readPublicKey("src/main/resources/key.pem");

String dataToEncrypt = "myMessage";
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypted = cipher.doFinal(dataToEncrypt.getBytes(StandardCharsets.UTF_8));

Tested with versions : bcpkix-jdk15on and bcprov-jdk15on.

Convert RSA Private Key to DER Format in Java

The OpenSSL statement converts the PEM encoded private key in PKCS#1 format into a DER encoded key in PKCS#8 format.

In Java, importing the PEM encoded PKCS#1 private key can be done with e.g. BouncyCastle's PEMParser and JcaPEMKeyConverter (using the bcprov und bcpkix jars). The export can be accomplished with PrivateKey#getEncoded() which returns the DER encoded PKCS#8 private key:

import java.io.FileOutputStream;
import java.io.FileReader;
import java.security.KeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
...
String inputFile = "<path to PKCS#1 PEM key>";
String outputFile = "<path to PKCS#8 DER key>";
try (FileReader fileReader = new FileReader(inputFile);
PEMParser pemParser = new PEMParser(fileReader);
FileOutputStream outputStream = new FileOutputStream(outputFile)) {
// Import PEM encoded PKCS#1 private key
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
KeyPair keyPair = converter.getKeyPair((PEMKeyPair)pemParser.readObject());
// Export DER encoded PKCS#8 private key
byte[] privateKey = keyPair.getPrivate().getEncoded();
outputStream.write(privateKey, 0, privateKey.length);
}

Convert PKCS#1-formatted private key to PKCS#8-formatted private key by java

Disclaimer: I did not come up with this solution myself, it was written by marcoscottwright over at github. Find the original code here


You can do so using BouncyCastle given you have a PrivateKey k object.

try (ASN1InputStream asn1InputStream = new ASN1InputStream(k.getEncoded()))
{
DERObject rsaPrivateKey = asn1InputStream.readObject();
return new PrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption), rsaPrivateKey).getDEREncoded();
}

RSA decryption according to the private key reports an error

1. You are decoding wrong. PEM format has a dash-BEGIN line identifying the type of data, a block of base64 encoding the data, and a dash-END line. The BEGIN and END lines are part of the format, but they do not contain base64-encoded data; only the lines in between contain the base64-encoded data. You are apparently passing the whole thing, including the BEGIN and END lines, to commons.codec.Base64, which results in decoding a bunch of garbage before and after the actual data. That garbage isn't valid ASN.1 DER, so when Java tries to parse it as DER it fails.

2. Plus your data is not a PKCS8-clear privatekey. The PEM type 'RSA PRIVATE KEY' is an OpenSSL-defined format that contains a 'traditional' or 'legacy' format, namely the PKCS1 representation of the private key. This is not PKCS8, which is the only key format Java supports natively; that's why the spec class is named PKCS8EncodedKeySpec, because it is a key spec encoded as PKCS8 and more specifically PKCS8-clear. If you fix the above problem by removing the BEGIN and END lines before base64-decoding, Java can parse the result as DER, but not as a PKCS8-clear key; you get a different exception about 'algid parse error, not a sequence'. To fix this there are 5 approaches:

  • change whatever process you use to initially generate the keypair so it generates PKCS8, not OpenSSL-legacy PKCS1. Especially since you need anyway to replace the keypair you compromised by publishing it, as 207421 said. You give no clue what that process is or was, so I can't give any details.

  • convert your generated privatekey, or a copy, to PKCS8-clear. This is not programming or development and offtopic, but if you have or get OpenSSL (on the same or any accessible and secure system), you can do

    openssl pkey -in oldfile -out newfile   # 1.0.0 up only, but older is now rare
    # or
    openssl pkcs8 -topk8 -nocrypt -in oldfile -out newfile # even ancient versions

Once you have a PKCS8-clear file, just remove the BEGIN and END lines and base64-decode what is left, and pass that to KeyFactory as PKCS8EncodedKeySpec as you already do.

  • use https://www.bouncycastle.org . The 'bcpkix' jar has (Java) code to read a large range of OpenSSL-supported PEM formats, including the RSA-PKCS1 private key format you have. There are lots of existing Qs about this; just search for PEMParser and JcaPEMKeyConverter.

  • convert it yourself. Decode the body of the file you have, after removing the BEGIN and END lines, to get the PKCS1 key, then build the PKCS8 format for that key, and then pass it to KeyFactory as PKCS8EncodedKeySpec. See answers by Noa Resare and Jean-Alexis Aufauvre on Getting RSA private key from PEM BASE64 Encoded private key file or mine in Java: Convert DKIM private key from RSA to DER for JavaMail .

  • do it entirely yourself. Decode the file you have without BEGIN/END to get PCKS1, parse that as DER following e.g. RFC8447, and build RSAPrivateCrtKeySpec. Some other As on the Q I linked just above do this. However, this requires either: using undocumented internal sun.* classes, which used to work in Java (hence the existing answers) but which 'modular' Java versions (9 up) since 2017 have steadily made more difficult or impossible; using BouncyCastle which has documented (and good) support for ASN.1 -- but then it's easier to use bcpkix for the whole job as above; or writing your own ASN.1 parsing, which is a good deal of work.

PS: encrypting text with RSA is usually a bad design; it's not suited for that. But that's not really a programming issue and doesn't belong here.

PKCS#1 and PKCS#8 format for RSA private key

PKCS#1 and PKCS#8 (Public-Key Cryptography Standard) are standards that govern the use of particular cryptographic primitives, padding, etc. Both define file formats that are used to store keys, certificates, and other relevant information.

PEM (Privacy-Enhanced Mail) and DER (Distinguished Encoding Rules) are a little bit more interesting. DER is the ASN.1 encoding for keys and certificates etc., which you'll be able to Google plenty about. Private keys and certificates are encoded using DER and can be saved directly like this. However, these files are binary and can't be copied and pasted easily, so many (if not most?) implementations accept PEM encoded files also. PEM is basically base64 encoded DER: we add a header, optional meta-data, and the base64 encoded DER data and we have a PEM file.



Related Topics



Leave a reply



Submit