InvalidKeySpecExeption when loadding the RSA private key from file

后端 未结 2 1706
时光说笑
时光说笑 2021-01-13 08:06

I\'m trying to load a private key from file in java. This key is generated by ssh-agent. I\'m actually using the code below:

     public PrivateKey getPrivat         


        
相关标签:
2条回答
  • 2021-01-13 08:08

    Are you sure its RSA ? also are you sure that the key is in the right format?

    If the answer is yes to both questions you can try using bouncycastle lib

    EDIT : Try removing these rows from the key:

    -----BEGIN RSA PRIVATE KEY-----
    .............................
    -----END RSA PRIVATE KEY-----
    

    UPDATE : make sure that you private key is in PKCS8 format if not you need to convert it like here

    0 讨论(0)
  • 2021-01-13 08:09

    Intstead of removing header and footers from private key file you can use BouncyCastle's Pemreader.

     private PrivateKey getPrivateKeyFromFile(String keyFile) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(keyFile);
        String privateKeySTr = IOUtils.toString(inputStream, String.valueOf(StandardCharsets.UTF_8));
    
        PemObject pem = new PemReader(new StringReader(privateKeySTr)).readPemObject();
        byte[] der = pem.getContent();
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(der);
        RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(ks);
        return privKey;
    }
    
    0 讨论(0)
提交回复
热议问题