Java. Security. Unrecoverablekeyexception: Get Key Failed: Null While Reading. P12 File in Java

I am trying to extract privateKey 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"

whats wrong that i am doing?

I am going nowhere as this private key will be used as a signer for creating Google JSON Web Token.

Thanks in advance.

1

1 Answer

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());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest