private static KeyStore saveCertificateAsKeyStore ( KeyStore existingKeyStore , boolean deleteOnExit , String keyStoreFileName , String certificationAlias , Key privateKey , char [ ] keyStorePassword , Certificate [ ] chain , X509Certificate caCert ) { try { KeyStore keyStore = existingKeyStore ; if ( keyStore == null ) { // create new key store keyStore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; keyStore . load ( null , keyStorePassword ) ; } // add certificate try { keyStore . deleteEntry ( certificationAlias ) ; } catch ( KeyStoreException kse ) { // ignore as may not exist in keystore yet } keyStore . setKeyEntry ( certificationAlias , privateKey , keyStorePassword , chain ) ; // add CA certificate try { keyStore . deleteEntry ( KEY_STORE_CA_ALIAS ) ; } catch ( KeyStoreException kse ) { // ignore as may not exist in keystore yet } keyStore . setCertificateEntry ( KEY_STORE_CA_ALIAS , caCert ) ; // save as JKS file String keyStoreFileAbsolutePath = new File ( keyStoreFileName ) . getAbsolutePath ( ) ; try ( FileOutputStream fileOutputStream = new FileOutputStream ( keyStoreFileAbsolutePath ) ) { keyStore . store ( fileOutputStream , keyStorePassword ) ; MOCK_SERVER_LOGGER . trace ( "Saving key store to file [" + keyStoreFileAbsolutePath + "]" ) ; } if ( deleteOnExit ) { new File ( keyStoreFileAbsolutePath ) . deleteOnExit ( ) ; } return keyStore ; } catch ( Exception e ) { throw new RuntimeException ( "Exception while saving KeyStore" , e ) ; } }
Save X509Certificate in KeyStore file .