问题
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
回答1:
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
.
回答2:
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
来源:https://stackoverflow.com/questions/20119874/how-to-load-the-private-key-from-a-der-file-into-java-private-key-object