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

社会主义新天地 提交于 2019-12-06 08:08:56

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.

thanks @gtrig using ur idea and editing the code like this :

            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(KeyBytes);  
            try 
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                privateKey = keyFactory.generatePrivate(keySpec);
                algorithm = keyFactory.getAlgorithm();
                //algorithm = "RSA";
                //publicKey = keyFactory.generatePublic(keySpec);
            } catch (InvalidKeySpecException excep1) {
                try {
                    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                    privateKey = keyFactory.generatePrivate(keySpec);
                    algorithm = keyFactory.getAlgorithm();
                    //publicKey = keyFactory.generatePublic(keySpec);
                } catch (InvalidKeySpecException excep2) {

                    KeyFactory keyFactory = KeyFactory.getInstance("EC");
                    privateKey = keyFactory.generatePrivate(keySpec);

                } // inner catch
            }

the code is working well now

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