KeystoreFactory { @SneakyThrows public RSAPrivateKey loadPrivateKey(String privateKeyLocation) { Resource keyRes = resourceLoader.getResource(privateKeyLocation); byte[] keyBytes = StreamUtils.copyToByteArray(keyRes.getInputStream()); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec); return privateKey; } KeystoreFactory();  KeystoreFactory(ResourceLoader resourceLoader); @SneakyThrows KeyStore loadKeystore(String certResourceLocation, String privateKeyResourceLocation, String alias, String keyPassword); @SneakyThrows void addKeyToKeystore(KeyStore keyStore, X509Certificate cert, RSAPrivateKey privateKey, String alias, String password); @SneakyThrows KeyStore createEmptyKeystore(); @SneakyThrows X509Certificate loadCert(String certLocation); @SneakyThrows RSAPrivateKey loadPrivateKey(String privateKeyLocation); void setResourceLoader(DefaultResourceLoader resourceLoader);  }
@Test public void loadKey() throws Exception { KeystoreFactory keystoreFactory = new KeystoreFactory(new DefaultResourceLoader()); RSAPrivateKey key = keystoreFactory.loadPrivateKey("classpath:/localhost.key.der"); assertThat(key.getAlgorithm()).isEqualTo("RSA"); assertThat(key.getFormat()).isEqualTo("PKCS#8"); }
@Test(expected = FileNotFoundException.class) public void loadKey_notFound() throws Exception { KeystoreFactory keystoreFactory = new KeystoreFactory(new DefaultResourceLoader()); RSAPrivateKey key = keystoreFactory.loadPrivateKey("classpath:/not_found.key.der"); }
@Test(expected = InvalidKeySpecException.class) public void loadKey_invalid() throws Exception { KeystoreFactory keystoreFactory = new KeystoreFactory(new DefaultResourceLoader()); RSAPrivateKey key = keystoreFactory.loadPrivateKey("classpath:/localhost.cert"); }