Search code examples
javaformatbouncycastlepkcs#8

how to load the private key from a .der file into java private key object


I'm writing a java program to import private keys from files within the file system and make a private key object, using java... I could do it for files in .pem format but, with .der format, I had no idea what to do, since I couldnt firstly detect the algorithm used to generate the keys. within .pem files I could determine the algorithm from the header for PKCS#1 which have a header like
-----BEGIN RSA PRIVATE KEY----
formats and used the bouncycastle pem reader for those in PKCS#8 which have a header
-----BEGIN PRIVATE KEY----- but with those in .der format no idea :(
also if anyone have an idea about .key format tell me
thanx


Solution

  • If your DER files are in PKCS#8 format, you can use the Java KeyFactory and do something like this:

    // Read file to a byte array.
    String privateKeyFileName = "C:\\myPrivateKey.der";   
    Path path = Paths.get(privateKeyFileName);
    byte[] privKeyByteArray = Files.readAllBytes(path);
    
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyByteArray);
    
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    
    PrivateKey myPrivKey = keyFactory.generatePrivate(keySpec);
    
    System.out.println("Algorithm: " + myPrivKey.getAlgorithm());
    

    You mentioned that you may not know what algorithm the key is using. I'm sure there is a more elegant solution than this, but you could create several KeyFactory objects (one for each possible algorithm) and try to generatePrivate() on each one until you do not get an InvalidKeySpecException.