且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将一个.der文件的私钥加载到java私钥对象中

更新时间:2023-12-02 20:51:10

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.