Java Code Examples for java.security.UnrecoverableKeyException

The following examples show how to use java.security.UnrecoverableKeyException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: localization_nifi   Source File: PostHTTP.java    License: Apache License 2.0 7 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    builder = builder.useProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example 2
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example 3
Source Project: msf4j   Source File: JWTSecurityInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private PublicKey getPublicKey(String keyStorePath, String keyStorePassword, String alias)
        throws IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException {

    try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(keyStorePath)) {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(inputStream, keyStorePassword.toCharArray());

        Key key = keystore.getKey(alias, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            // Get certificate of public key
            java.security.cert.Certificate cert = keystore.getCertificate(alias);

            // Get public key
            return cert.getPublicKey();
        }
    }
    return null;
}
 
Example 4
public JumbleSSLSocketFactory(KeyStore keystore, String keystorePassword, String trustStorePath, String trustStorePassword, String trustStoreFormat) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, NoSuchProviderException, IOException, CertificateException {
    mContext = SSLContext.getInstance("TLS");

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : new char[0]);

    if(trustStorePath != null) {
        KeyStore trustStore = KeyStore.getInstance(trustStoreFormat);
        FileInputStream fis = new FileInputStream(trustStorePath);
        trustStore.load(fis, trustStorePassword.toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        mTrustWrapper = new JumbleTrustManagerWrapper((X509TrustManager) tmf.getTrustManagers()[0]);
        Log.i(Constants.TAG, "Using custom trust store " + trustStorePath + " with system trust store");
    } else {
        mTrustWrapper = new JumbleTrustManagerWrapper(null);
        Log.i(Constants.TAG, "Using system trust store");
    }

    mContext.init(kmf.getKeyManagers(), new TrustManager[] { mTrustWrapper }, null);
}
 
Example 5
public static byte[] unseal(byte[] data) throws IntegrationModuleException {
   try {
      EncryptionUtils encryptionUtils = EncryptionUtils.getInstance();
      DataUnsealer dataUnsealer = encryptionUtils.initUnsealing();
      return encryptionUtils.unsealingData(dataUnsealer.unseal(data));
   } catch (KeyStoreException var3) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var3);
   } catch (UnrecoverableKeyException var4) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var4);
   } catch (NoSuchAlgorithmException var5) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var5);
   } catch (CertificateException var6) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var6);
   } catch (IOException var7) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var7);
   }
}
 
Example 6
Source Project: intellij-demandware   Source File: DWServerConnection.java    License: MIT License 6 votes vote down vote up
public DWServerConnection(DWSettingsProvider settingsProvider) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    this.settingsProvider = settingsProvider;

    // SSLContextFactory to allow all hosts. Without this an SSLException is thrown with self signed certs
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connectionManager.setMaxTotal(200);
    connectionManager.setDefaultMaxPerRoute(20);

    client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();

    context = new HttpClientContext();
    context.setCredentialsProvider(getCredientials());
}
 
Example 7
Source Project: cloudstack   Source File: RootCAProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SSLEngine createSSLEngine(final SSLContext sslContext, final String remoteAddress, final Map<String, X509Certificate> certMap) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

    final KeyStore ks = getCaKeyStore();
    kmf.init(ks, getKeyStorePassphrase());
    tmf.init(ks);

    final boolean authStrictness = rootCAAuthStrictness.value();
    final boolean allowExpiredCertificate = rootCAAllowExpiredCert.value();

    TrustManager[] tms = new TrustManager[]{new RootCACustomTrustManager(remoteAddress, authStrictness, allowExpiredCertificate, certMap, caCertificate, crlDao)};
    sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
    final SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setNeedClientAuth(authStrictness);
    return sslEngine;
}
 
Example 8
Source Project: localization_nifi   Source File: SslContextFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a SSLContext instance using the given information.
 *
 * @param keystore the full path to the keystore
 * @param keystorePasswd the keystore password
 * @param keystoreType the type of keystore (e.g., PKCS12, JKS)
 * @param protocol the protocol to use for the SSL connection
 *
 * @return a SSLContext instance
 * @throws java.security.KeyStoreException if any issues accessing the keystore
 * @throws java.io.IOException for any problems loading the keystores
 * @throws java.security.NoSuchAlgorithmException if an algorithm is found to be used but is unknown
 * @throws java.security.cert.CertificateException if there is an issue with the certificate
 * @throws java.security.UnrecoverableKeyException if the key is insufficient
 * @throws java.security.KeyManagementException if unable to manage the key
 */
public static SSLContext createSslContext(
    final String keystore, final char[] keystorePasswd, final char[] keyPasswd, final String keystoreType, final String protocol)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStoreUtils.getKeyStore(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (keyPasswd == null) {
        keyManagerFactory.init(keyStore, keystorePasswd);
    } else {
        keyManagerFactory.init(keyStore, keyPasswd);
    }

    // initialize the ssl context
    final SSLContext ctx = SSLContext.getInstance(protocol);
    ctx.init(keyManagerFactory.getKeyManagers(), new TrustManager[0], new SecureRandom());

    return ctx;

}
 
Example 9
Source Project: android_9.0.0_r45   Source File: RecoverySession.java    License: Apache License 2.0 6 votes vote down vote up
/** Given a map from alias to grant alias, returns a map from alias to a {@link Key} handle. */
private @NonNull Map<String, Key> getKeysFromGrants(@NonNull Map<String, String> grantAliases)
        throws InternalRecoveryServiceException {
    ArrayMap<String, Key> keysByAlias = new ArrayMap<>(grantAliases.size());
    for (String alias : grantAliases.keySet()) {
        String grantAlias = grantAliases.get(alias);
        Key key;
        try {
            key = mRecoveryController.getKeyFromGrant(grantAlias);
        } catch (UnrecoverableKeyException e) {
            throw new InternalRecoveryServiceException(
                    String.format(
                            Locale.US,
                            "Failed to get key '%s' from grant '%s'",
                            alias,
                            grantAlias), e);
        }
        keysByAlias.put(alias, key);
    }
    return keysByAlias;
}
 
Example 10
Source Project: localization_nifi   Source File: GetHTTP.java    License: Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())){
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example 11
public void addKeyStore(KeyStore keyStore, String keystorePass){
	synchronized (keyManagers) {
		try {
			KeyManagerFactory factory =
				KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			factory.init(keyStore, keystorePass.toCharArray());
			KeyManager[] managers = factory.getKeyManagers();
			List<X509KeyManager> typedManagers = new ArrayList<>();
			for (KeyManager keyManager : managers) {
				if (keyManager instanceof X509KeyManager) {
					typedManagers.add((X509KeyManager) keyManager);
				}
			}
			keyManagers.put(keyStore, typedManagers);
		} catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
			LoggerFactory.getLogger(getClass()).error("Could not add trust store", e);
		}
	}
}
 
Example 12
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example 13
Source Project: nifi-registry   Source File: SslContextFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a SSLContext instance using the given information.
 *
 * @param keystore the full path to the keystore
 * @param keystorePasswd the keystore password
 * @param keystoreType the type of keystore (e.g., PKCS12, JKS)
 * @param protocol the protocol to use for the SSL connection
 *
 * @return a SSLContext instance
 * @throws KeyStoreException if any issues accessing the keystore
 * @throws IOException for any problems loading the keystores
 * @throws NoSuchAlgorithmException if an algorithm is found to be used but is unknown
 * @throws CertificateException if there is an issue with the certificate
 * @throws UnrecoverableKeyException if the key is insufficient
 * @throws KeyManagementException if unable to manage the key
 */
public static SSLContext createSslContext(
    final String keystore, final char[] keystorePasswd, final char[] keyPasswd, final String keystoreType, final String protocol)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStoreUtils.getKeyStore(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (keyPasswd == null) {
        keyManagerFactory.init(keyStore, keystorePasswd);
    } else {
        keyManagerFactory.init(keyStore, keyPasswd);
    }

    // initialize the ssl context
    final SSLContext ctx = SSLContext.getInstance(protocol);
    ctx.init(keyManagerFactory.getKeyManagers(), new TrustManager[0], new SecureRandom());

    return ctx;

}
 
Example 14
Source Project: arcusplatform   Source File: BridgeServerTlsContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
private static KeyManagerFactory createKeyManagerFactory(BridgeServerConfig serverConfig)
   throws IOException, KeyStoreException, CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException {
   String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
   if (algorithm == null) {
      algorithm = "SunX509";
   }

   KeyStore ks = KeyStoreLoader.loadKeyStore(
      serverConfig.getTlsServerKeystoreFilepath(),
      serverConfig.getTlsServerKeystorePassword()
   );

   KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
   kmf.init(ks, serverConfig.getTlsServerKeyPassword().toCharArray());

   return kmf;
}
 
Example 15
Source Project: lucene-solr   Source File: SSLTestConfig.java    License: Apache License 2.0 6 votes vote down vote up
public SSLConfig buildClientSSLConfig() {
  if (!isSSLMode()) {
    return null;
  }

  return new SSLConfig(isSSLMode(), isClientAuthMode(), null, null, null, null) {
    @Override
    public SslContextFactory.Client createClientContextFactory() {
      SslContextFactory.Client factory = new SslContextFactory.Client(!checkPeerName);
      try {
        factory.setSslContext(buildClientSSLContext());
      } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IllegalStateException("Unable to setup https scheme for HTTPClient to test SSL.", e);
      }
      return factory;
    }
  };
}
 
Example 16
/**
 * {@inheritDoc}
 */
@Nullable
@Override
public String decrypt(String alias) {
    try {
        byte[] storedData = storage.getKeyBytes(alias);
        if (storedData == null) {
            return null;
        }
        KeyStore keyStore = getKeyStoreAndLoad();
        Key key = keyStore.getKey(alias, null);
        if (key == null) {
            /* Well this should not happen if you do not have a stored byte data, but just in case */
            return null;
        }
        return decryptBytes(key, storedData);
    } catch (KeyStoreException | UnrecoverableKeyException |
            NoSuchAlgorithmException | KeyStoreAccessException e) {
        return null;
    }
}
 
Example 17
/***
 * Reads the  (private) key and certificate from keystore to sign
 * 
 * @throws OfficeWriterException
 * @throws IOException
 */
private void readSigningKeyAndCertificate() throws OfficeWriterException, IOException {
	if ((this.howc.getSigKeystoreFile()!=null) && (!"".equals(this.howc.getSigKeystoreFile()))) {
		LOG.info("Signing document");
		if ((this.howc.getSigKeystoreAlias()==null) || ("".equals(this.howc.getSigKeystoreAlias()))) {
				LOG.error("Keystore alias for signature keystore not defined. Cannot sign document");
				throw new OfficeWriterException("Keystore alias for signature keystore not defined. Cannot sign document");
		}
		if ((this.howc.getSigKeystoreType()==null) || ("".equals(this.howc.getSigKeystoreType()))) {
			LOG.error("Keystore type for signature keystore not defined. Cannot sign document");
			throw new OfficeWriterException("Keystore type for signature keystore not defined. Cannot sign document");
		}
		LOG.info("Reading keystore");
		FlinkKeyStoreManager fksm = new FlinkKeyStoreManager();
		try {
			fksm.openKeyStore(new Path(this.howc.getSigKeystoreFile()), this.howc.getSigKeystoreType(), this.howc.getSigKeystorePassword());
			this.howc.setSigKey(fksm.getPrivateKey(this.howc.getSigKeystoreAlias(), this.howc.getSigKeystorePassword()));
			this.howc.setSigCertificate((X509Certificate) fksm.getCertificate(this.howc.getSigKeystoreAlias()));
		} catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IllegalArgumentException | UnrecoverableKeyException  e) {
			LOG.error("Cannopt read signing certificate. Exception: ",e);
			throw new OfficeWriterException("Cannot read keystore to obtain key and certificate for signing "+e);
		}
		
		
	}
}
 
Example 18
@Override
public SSLContext getSSLContext()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {

    try {
        final KeyStore keyStore = CertificateUtils.createKeyStore(credentials.getClientKey(),
                credentials.getClientCertificate());
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "docker".toCharArray());
        final KeyStore trustStore = CertificateUtils.createTrustStore(credentials.getServerCaCertificate());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        final SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        return context;
    } catch (CertificateException | InvalidKeySpecException | IOException e) {
        throw new KeyStoreException("Can't build keystore from provided client key/certificate", e);
    }
}
 
Example 19
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example 20
public void testAliasWithIncorrectPassword_One() throws Exception
    {
        try
        {
        	getTestKeyStoreProvider(FILE_ONE, Collections.singletonMap(ALIAS_ONE, "password_fail"));	
        	
//            new KeystoreKeyProvider(
//                    FILE_ONE,
//                    getKeyStoreLoader(),
//                    "SunJCE",
//                    "JCEKS",
//                    Collections.singletonMap(ALIAS_ONE, "password_fail"));
            fail("Expect to fail because password is incorrect");
        }
        catch (AlfrescoRuntimeException e)
        {
            // Expected
            assertTrue(e.getCause() instanceof UnrecoverableKeyException);
        }
    }
 
Example 21
Source Project: fabric-sdk-java   Source File: CryptoPrimitivesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
// TODO need to regen key now that we're using CryptoSuite
public void testSign() {

    byte[] plainText = "123456".getBytes(UTF_8);
    byte[] signature;
    try {
        PrivateKey key = (PrivateKey) crypto.getTrustStore().getKey("key", "123456".toCharArray());
        signature = crypto.sign(key, plainText);

        BufferedInputStream bis = new BufferedInputStream(
                this.getClass().getResourceAsStream("/keypair-signed.crt"));
        byte[] cert = IOUtils.toByteArray(bis);
        bis.close();

        assertTrue(crypto.verify(cert, SIGNING_ALGORITHM, signature, plainText));
    } catch (KeyStoreException | CryptoException | IOException | UnrecoverableKeyException
            | NoSuchAlgorithmException e) {
        fail("Could not verify signature. Error: " + e.getMessage());
    }
}
 
Example 22
Source Project: kogito-runtimes   Source File: KeyStoreHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates the signature for the given byte[] using MD5 with RSA algorithm and the
 * private key with which this helper was initialised.
 *
 * @param data the byte[] of data to be signed
 *
 * @return the signature, encrypted with the private key
 *
 * @throws UnrecoverableKeyException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public byte[] signDataWithPrivateKey(byte[] data) throws UnrecoverableKeyException,
                                                 KeyStoreException,
                                                 NoSuchAlgorithmException,
                                                 InvalidKeyException,
                                                 SignatureException {
    if( pvtKeyStore == null ) {
        throw new RuntimeException( "Key store with private key not configured. Please configure it properly before using signed serialization." );
    }
    PrivateKey pvtkey = (PrivateKey) pvtKeyStore.getKey( pvtKeyAlias,
                                                         pvtKeyPassword );
    Signature sig = Signature.getInstance( "MD5withRSA" );
    sig.initSign( pvtkey );
    sig.update( data );
    return sig.sign();
}
 
Example 23
Source Project: brooklyn-server   Source File: JmxmpClient.java    License: Apache License 2.0 6 votes vote down vote up
/** tries to connect to the given JMX url over tls, 
 * optionally using the given keystore (if null using a randomly generated key)
 * and optionally using the given truststore (if null trusting all) */
public void connectTls(String urlString, KeyStore keyStore, String keyStorePass, KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, InvalidKeyException, CertificateException, SecurityException, SignatureException, IOException, KeyManagementException { 
    Map env = new LinkedHashMap(); 

    env.put("jmx.remote.profiles", JmxmpAgent.TLS_JMX_REMOTE_PROFILES);

    if (keyStore==null) throw new NullPointerException("keyStore must be supplied");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); //"SunX509");
    kmf.init(keyStore, (keyStorePass!=null ? keyStorePass : "").toCharArray());

    TrustManager tms = trustStore!=null ? SecureKeys.getTrustManager(trustStore) : SslTrustUtils.TRUST_ALL;

    SSLContext ctx = SSLContext.getInstance("TLSv1");
    ctx.init(kmf.getKeyManagers(), new TrustManager[] { tms }, null);
    SSLSocketFactory ssf = ctx.getSocketFactory(); 
    env.put(JmxmpAgent.TLS_SOCKET_FACTORY_PROPERTY, ssf); 

    connect(urlString, env); 
}
 
Example 24
Source Project: ethsigner   Source File: CertificateHelpers.java    License: Apache License 2.0 5 votes vote down vote up
public static KeyManager[] createKeyManagers(final TlsCertificateDefinition certToPresent)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
  if (certToPresent == null) {
    return null;
  }

  final String password = certToPresent.getPassword();

  final KeyStore clientCertStore = loadP12KeyStore(certToPresent.getPkcs12File(), password);

  final KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
  kmf.init(clientCertStore, password.toCharArray());
  return kmf.getKeyManagers();
}
 
Example 25
Source Project: ranger   Source File: AzureKeyVaultClientAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
private KeyCert readPfx(String path, String password) throws NoSuchProviderException, KeyStoreException,
		IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
	try (FileInputStream stream = new FileInputStream(path)) {
		KeyCert keyCert = new KeyCert();
		boolean isAliasWithPrivateKey = false;
		final KeyStore store = KeyStore.getInstance("pkcs12", "SunJSSE");
		store.load((InputStream) stream, password.toCharArray());

		// Iterate over all aliases to find the private key
		Enumeration<String> aliases = store.aliases();
		String alias = "";
		while (aliases.hasMoreElements()) {
			alias = aliases.nextElement();
			// Break if alias refers to a private key because we want to use that
			// certificate
			if (isAliasWithPrivateKey = store.isKeyEntry(alias)) {
				break;
			}
		}
		if (isAliasWithPrivateKey) {
			// Retrieves the certificate from the Java keystore
			X509Certificate certificate = (X509Certificate) store.getCertificate(alias);
			PrivateKey key = (PrivateKey) store.getKey(alias, password.toCharArray());
			keyCert.setCertificate(certificate);
			keyCert.setKey(key);
		}
		return keyCert;
	}
}
 
Example 26
Source Project: RxFingerprint   Source File: AesCipherProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
Cipher cipherForEncryption() throws NoSuchAlgorithmException, NoSuchPaddingException, CertificateException, UnrecoverableKeyException, KeyStoreException, NoSuchProviderException, InvalidAlgorithmParameterException, IOException, InvalidKeyException {
	Cipher cipher = createCipher();
	SecretKey key = findOrCreateKey(keyName);
	cipher.init(Cipher.ENCRYPT_MODE, key);
	return cipher;
}
 
Example 27
public static byte[] seal(byte[] data, SecretKey secretKey, String keyId) throws IntegrationModuleException {
    try {
        DataSealer dataSealer = EncryptionUtils.getInstance().initSealing();
        return dataSealer.seal(data, secretKey, keyId);
    } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | CertificateException | IOException | DataSealerException ex) {
        throw new IntegrationModuleException("technical.connector.error.data.seal", ex);
    }
}
 
Example 28
private ApkSigner.SignerConfig loadKeyStore(String keyStoreType, String keyStorePassword) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
  KeyStore keyStoreEntity = KeyStore.getInstance(keyStoreType == null ? KeyStore.getDefaultType() : keyStoreType);
  char[]   password       = getPassword(keyStorePassword);
  keyStoreEntity.load(null, password);

  Enumeration<String> aliases  = keyStoreEntity.aliases();
  String              keyAlias = null;

  while (aliases != null && aliases.hasMoreElements()) {
    String alias = aliases.nextElement();
    if (keyStoreEntity.isKeyEntry(alias)) {
      keyAlias = alias;
      break;
    }
  }

  if (keyAlias == null) {
    throw new IllegalArgumentException("Keystore has no key entries!");
  }

  PrivateKey    privateKey   = (PrivateKey) keyStoreEntity.getKey(keyAlias, password);
  Certificate[] certificates = keyStoreEntity.getCertificateChain(keyAlias);

  if (certificates == null || certificates.length == 0) {
    throw new IllegalArgumentException("Unable to load certificates!");
  }

  List<X509Certificate> results = new LinkedList<>();

  for (Certificate certificate : certificates) {
    results.add((X509Certificate)certificate);
  }


  return new ApkSigner.SignerConfig.Builder("Signal Signer", privateKey, results).build();
}
 
Example 29
Source Project: java-n-IDE-for-Android   Source File: JKS.java    License: Apache License 2.0 5 votes vote down vote up
public Key engineGetKey(String alias, char[] password)
    throws NoSuchAlgorithmException, UnrecoverableKeyException
{
    alias = alias.toLowerCase();

    if (!privateKeys.containsKey(alias))
        return null;
    byte[] key = decryptKey((byte[]) privateKeys.get(alias),
        charsToBytes(password));
    Certificate[] chain = engineGetCertificateChain(alias);
    if (chain.length > 0)
    {
        try
        {
            // Private and public keys MUST have the same algorithm.
            KeyFactory fact = KeyFactory.getInstance(
                chain[0].getPublicKey().getAlgorithm());
            return fact.generatePrivate(new PKCS8EncodedKeySpec(key));
        }
        catch (InvalidKeySpecException x)
        {
            throw new UnrecoverableKeyException(x.getMessage());
        }
    }
    else
        return new SecretKeySpec(key, alias);
}
 
Example 30
Source Project: ranger   Source File: NiFiRegistryConnectionMgr.java    License: Apache License 2.0 5 votes vote down vote up
private static SSLContext createSslContext(
        final String keystore, final char[] keystorePasswd, final String keystoreType,
        final String truststore, final char[] truststorePasswd, final String truststoreType,
        final String protocol)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePasswd);

    // prepare the truststore
    final KeyStore trustStore = KeyStore.getInstance(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext sslContext = SSLContext.getInstance(protocol);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    return sslContext;
}