I am trying to read a private key i java .I learned inorder to do that i have to extract private key from my full certificate in pfx format. I have tried the below open ssl command to convert pfx to pem and then to pk8 , but when i tried to read the key in java , it says invalid key format
convert pfx to pem
openssl pkcs12 -in C:\Documents\xbox-token\conversion\xbox
token-FullCert.pfx -nocerts -out C:\Documents\xbox-token\conversion\xboxkey.pem
Removing password protection
openssl rsa -in C:\Documents\xbox-token\conversion\xboxkey.pem -out C:\Documents\xbox-token\conversion\xboxkey.pem
Convert pem to pk8
openssl pkcs8 -topk8 -in C:\Documents\xbox-token\conversion\xboxkey.pem -out C:\Documents\xbox-token\conversion\xboxprv.pk8
In the java code
byte[] encodedPrivateKey=null;
File privateKeyFile = new File("C:/Documents/xbox-token/conversion/xboxprv.pk8");
FileInputStream inputStreamPrivateKey = null;
try {
inputStreamPrivateKey = new FileInputStream(privateKeyFile);
encodedPrivateKey = new byte[(int)privateKeyFile.length()];
inputStreamPrivateKey.read(encodedPrivateKey);
inputStreamPrivateKey.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Create the private key.
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
System.out.println(encodedPrivateKey);
System.out.println(privateKeySpec);
RSAPrivateKey privateKey = null;
try {
privateKey = (RSAPrivateKey)KeyFactory.getInstance("RSA").generatePrivate(privateKeySpec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am getting an java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
Can any one help