Search code examples
javapem

How do I properly Read a PEM PrivateKey


I'm trying to read a private key for a JWT generation but get an error:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : null.

I simplified the code to use some valid base64 key but still got this error.

private PrivateKey getPrivateKey() throws Exception
{
   String privateKeyPEMFormatted = 
"MIIBVgIBADANBgkqhkiG9w0BAQEFAASCATwwggE4AgEAAkEAzPUG7l/N0B5wr7TxF0+5Uxl5GZJ9N7ck+l5lUGM3yMR5YVqekZ6J0ON5nFfTmT3Tx5h+u5YKhzZ/bHYf8bFg9wIDAQABAkAAvNjEzfDbBVeBGWRCGhfM4kQFdyI9IoO2HJ6WgdSZK/LQvdSMbJf6e4O08Kj2FSq+O1WLPoT3sQ4lNaaRQ+2hAiEA+u5tQFcmFUVZsZb+uD/FXNdBlRXI/D7L4Ib4Nnb3OgECIQDYfhFPBeROr9tQRYNhuWmfGAtSjaKlG2cGQXYMlyiNVwIgCcLr5G6eGHiz7E9aPyRQo/1Wn+5x3w9Z0P1pX6QEzL8CIQCET+ZWAA8lfvTofU8QzXpJcN9L5xROOZ1TGyz+jmiOFQIhAK9F1mpOKkFdTLDXrdypo+5rAhnxqV2P9Hp+1vKQtZ9x";

   byte[] decoded =Base64.getDecoder().decode(privateKeyPEMFormatted);
   PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
   KeyFactory kf = KeyFactory.getInstance("RSA");
   return kf.generatePrivate(spec);
}

I've read all posts here about it but still can't find a solution...


Solution

  • First your Base64 key is somehow corrupted. Your code is fine with a example private key as follows from here.

    private PrivateKey getPrivateKey() throws Exception
    {
       String privateKeyPEMFormatted = 
    "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqPfgaTEWEP3S9w0tgsicURfo+nLW09/0KfOPinhYZ4ouzU+3xC4pSlEp8Ut9FgL0AgqNslNaK34Kq+NZjO9DAQIDAQABAkAgkuLEHLaqkWhLgNKagSajeobLS3rPT0Agm0f7k55FXVt743hwNgkp98bMNrzy9AQ1mJGbQZGrpr4c8ZAx3aRNAiEAoxK/MgGeeLui385KJ7ZOYktjhLBNAB69fKwTZFsUNh0CIQEJQRpFCcydunv2bENcN/oBTRw39E8GNv2pIcNxZkcbNQIgbYSzn3Py6AasNj6nEtCfB+i1p3F35TK/87DlPSrmAgkCIQDJLhFoj1gbwRbH/bDRPrtlRUDDx44wHoEhSDRdy77eiQIgE6z/k6I+ChN1LLttwX0galITxmAYrOBhBVl433tgTTQ=";
    
    byte[] decoded = Base64.getDecoder().decode(privateKeyPEMFormatted);
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
    }
    

    I believe the correct way to read a PEM formatted private key is like this