PemReader { public static PrivateKey loadPrivateKey(File privateKeyFile, Optional<String> keyPassword) throws IOException, GeneralSecurityException { String privateKey = new String(Files.readAllBytes(privateKeyFile.toPath()), US_ASCII); return loadPrivateKey(privateKey, keyPassword); } private  PemReader(); static KeyStore loadTrustStore(File certificateChainFile); static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, Optional<String> keyPassword); static List<X509Certificate> readCertificateChain(File certificateChainFile); static List<X509Certificate> readCertificateChain(String certificateChain); static PrivateKey loadPrivateKey(File privateKeyFile, Optional<String> keyPassword); static PrivateKey loadPrivateKey(String privateKey, Optional<String> keyPassword); static PublicKey loadPublicKey(File publicKeyFile); static PublicKey loadPublicKey(String publicKey);  }
@Test public void testLoadPrivateKeyFromKeyStore() throws IOException, GeneralSecurityException { Optional<String> optPassword = x509TestContext.getKeyStorePassword().length() > 0 ? Optional.of(x509TestContext.getKeyStorePassword()) : Optional.empty(); PrivateKey privateKey = PemReader.loadPrivateKey( x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM), optPassword); Assert.assertEquals(x509TestContext.getKeyStoreKeyPair().getPrivate(), privateKey); }
@Test(expected = GeneralSecurityException.class) public void testLoadEncryptedPrivateKeyFromKeyStoreWithoutPassword() throws GeneralSecurityException, IOException { if (!x509TestContext.isKeyStoreEncrypted()) { throw new GeneralSecurityException(); } PemReader.loadPrivateKey(x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM), Optional.empty()); }
@Test(expected = GeneralSecurityException.class) public void testLoadEncryptedPrivateKeyFromKeyStoreWithWrongPassword() throws GeneralSecurityException, IOException { if (!x509TestContext.isKeyStoreEncrypted()) { throw new GeneralSecurityException(); } PemReader.loadPrivateKey( x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM), Optional.of("wrong password")); }
@Test(expected = IOException.class) public void testLoadUnencryptedPrivateKeyFromKeyStoreWithWrongPassword() throws GeneralSecurityException, IOException { if (x509TestContext.isKeyStoreEncrypted()) { throw new IOException(); } PemReader.loadPrivateKey( x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM), Optional.of("wrong password")); }
@Test(expected = KeyStoreException.class) public void testLoadPrivateKeyFromTrustStore() throws IOException, GeneralSecurityException { PemReader.loadPrivateKey( x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM), Optional.empty()); }
@Test(expected = KeyStoreException.class) public void testLoadPrivateKeyFromTrustStoreWithPassword() throws IOException, GeneralSecurityException { PemReader.loadPrivateKey( x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM), Optional.of("foobar")); }