public static PrivateKey decodePrivateKey ( String pemEncoded ) throws Exception { pemEncoded = removeBeginEnd ( pemEncoded ) ; byte [ ] pkcs8EncodedBytes = Base64 . getDecoder ( ) . decode ( pemEncoded ) ; // extract the private key PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec ( pkcs8EncodedBytes ) ; KeyFactory kf = KeyFactory . getInstance ( "RSA" ) ; PrivateKey privKey = kf . generatePrivate ( keySpec ) ; return privKey ; }
Decode a PEM encoded private key string to an RSA PrivateKey