PrivateKeyReader { public static PrivateKey fromPem(Path path, String password) { PrivateKey privateKey; try { byte[] der = getDer(path); KeySpec keySpec = getKeySpec(der, password); KeyFactory kf = KeyFactory.getInstance("RSA"); privateKey = kf.generatePrivate(keySpec); } catch (Exception e) { String msg = String.format("Failed to read PKCS#8 PEM file. file=%s", path); Utils.logWarning(msg); throw new RuntimeException(msg, e); } return privateKey; } private  PrivateKeyReader(); static PrivateKey fromPem(Path path, String password);  }
@Test public void readNonEncryptedPemPrivateKey() throws Exception { Path path = Paths.get(getClass().getResource("/ssl/server.pem").toURI()); PrivateKey privateKey = PrivateKeyReader.fromPem(path, null); assertNotNull(privateKey); assertEquals("PKCS#8", privateKey.getFormat()); try { PrivateKeyReader.fromPem(path, ""); fail("Should fail with empty password"); } catch (Exception ex) { } try { PrivateKeyReader.fromPem(path, "password"); fail("Should fail with any password for non encrypted key"); } catch (Exception ex) { } }
@Test public void readEncryptedPemPrivateKey() throws Exception { Path path = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI()); PrivateKey privateKey = PrivateKeyReader.fromPem(path, "password"); assertNotNull(privateKey); assertEquals("PKCS#8", privateKey.getFormat()); try { PrivateKeyReader.fromPem(path, null); fail("Should fail with null password"); } catch (Exception ex) { } try { PrivateKeyReader.fromPem(path, ""); fail("Should fail with empty password"); } catch (Exception ex) { } try { PrivateKeyReader.fromPem(path, "wrong-password"); fail("Should fail with wrong password"); } catch (Exception ex) { } }