Monim
Monim

Reputation: 3577

how to determine the algorithm used to generate a private key from a .pem file using java

I'm trying to read a private key from a .pem file in PKCS#8 format, the problem I've faced is that these kind of files have this header -----BEGIN PRIVATE KEY----- so there is no information about the algorithm used to instantiate the key, my question is:
is there a method to know the algorithm without decoding the key (which is base64) and see the algorithm modifier, also if there is a way to know the length of the key.. help is appreciated

Upvotes: 2

Views: 4244

Answers (1)

gtrig
gtrig

Reputation: 12958

Using Bouncy Castle and modifying the code from this answer, I came up with this to get your answers.

Note: This code will only work with non-encrypted private keys.

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.Security;

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jcajce.provider.asymmetric.dsa.BCDSAPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPrivateKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

public class PemKeyInfo 
{
/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException 
{
    Security.addProvider(new BouncyCastleProvider());

    String privateKeyFileName = "C:\\privkeypk8.pem";

    File privateKeyFile = new File(privateKeyFileName); // private key file in PEM format
    PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
    Object object = pemParser.readObject();

    pemParser.close();

    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

    PrivateKey privkey = null;

    if (object instanceof PrivateKeyInfo)
    {
       privkey = converter.getPrivateKey((PrivateKeyInfo) object);
    }
    if (privkey != null)
    {
       System.out.println("Algorithm: " + privkey.getAlgorithm()); // ex. RSA
       System.out.println("Format: " + privkey.getFormat()); // ex. PKCS#8
    }
    if (privkey instanceof BCRSAPrivateKey)
    {
       System.out.println("RSA Key Length: " + ((BCRSAPrivateKey)privkey).getModulus().bitLength()); // ex. 2048
    }
    if (privkey instanceof BCDSAPrivateKey)
    {
       System.out.println("DSA Key Length: " + ((BCDSAPrivateKey)privkey).getParams().getP().bitLength()); // ex. 2048
    }
    if (privkey instanceof BCECPrivateKey)
    {
       System.out.println("EC Key Length: " + ((BCECPrivateKey)privkey).getParams().getOrder().bitLength()); // ex. 256
    }
  }
}

Update: I've edited the code above to give key lengths for RSA, DSA, and EC keys.

Upvotes: 1

Related Questions