private static PrivateKey readPrivateKey(InputStream input) throws IOException, GeneralSecurityException { try { byte[] bytes = ByteBuffer.getBytes(input); KeySpec spec = Signer.decryptPrivateKey(bytes); if (spec == null) { spec = new PKCS8EncodedKeySpec(bytes); } try { return KeyFactory.getInstance("RSA").generatePrivate(spec); } catch (InvalidKeySpecException ex) { return KeyFactory.getInstance("DSA").generatePrivate(spec); } } finally { input.close(); } }