Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.security.UnrecoverableKeyException: Get Key failed: null while reading .p12 file in Java

Tags:

java

keystore

I am trying to extract the private key from a .p12 file downloaded from Google Service Account Console.

I am reading this .p12 from the folder location and creating the KeyStore object.

KeyStore myStore = null;
FileInputStream in_cert = new FileInputStream(
                "D://Google Analytics//login//GA//6aa55af54232dfa60b60a908ff0138bba1147d63-privatekey.p12");

myStore = KeyStore.getInstance("PKCS12");
myStore.load(in_cert, null); // if i give "changeit" as the password(hopefully the default keystore password) gets the exception "java.security.UnrecoverableKeyException: Get Key failed: Given final block not properly padded. If null is passed as an argument the program runs fine with output as "privatekey""

Enumeration<String> aliases = myStore.aliases();
String alias = "";
System.out.println(myStore.aliases());

while (aliases.hasMoreElements()) {
    System.out.println(aliases.nextElement()); // prints privatekey
}

java.security.PrivateKey privateKey = (PrivateKey) myStore.getKey("privatekey", null); // gives exception "java.security.UnrecoverableKeyException: Get Key failed: null"

What's wrong that I am doing?

I need the private key as a signer for creating Google JSON Web Token.

like image 802
prathamesh_mb Avatar asked Nov 14 '13 11:11

prathamesh_mb


1 Answers

Just in case somebody lands here, as mentioned by @prathamesh_mb, you need to provide the password while loading the key.

PrivateKey privateKey = (PrivateKey) myStore.getKey("privatekey", "yourpasswordhere".toCharArray());
like image 118
divinedragon Avatar answered Oct 21 '22 05:10

divinedragon