java.security.KeyStoreException Java Examples

The following examples show how to use java.security.KeyStoreException. 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 File: CustomHttpClient.java    From zerocode-hello-world with MIT License 6 votes vote down vote up
/**
 * This method has been overridden here simply to show how a custom/project-specific http client
 * can be plugged into the framework.
 *
 * e.g. You can create your own project specific http client needed for http/https/tls connections or
 * a Corporate proxy based Http client here.
 * Sometimes you may need a simple default http client
 * e.g. HttpClients.createDefault() provided by Apache lib.
 *
 * Note:
 * If you do not override this method, the framework anyways creates a http client suitable for both http/https.
 */
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .build();
}
 
Example #2
Source File: MetadataEmptyTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 File: X509CertUtil.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check whether or not a trusted certificate in the supplied keystore matches the the supplied X.509 certificate.
 *
 * @return The alias of the matching certificate in the keystore or null if there is no match
 * @param cert The certificate
 * @param keyStore The keystore
 * @throws CryptoException If there is a problem establishing trust
 */
public static String matchCertificate(KeyStore keyStore, X509Certificate cert)
    throws CryptoException
{
	try
	{
		for (Enumeration<String> en = keyStore.aliases(); en.hasMoreElements();)
		{
			String sAlias = en.nextElement();
			if (keyStore.isCertificateEntry(sAlias))
			{
				X509Certificate compCert = X509CertUtil.convertCertificate(keyStore.getCertificate(sAlias));

				if (cert.equals(compCert))
				{
					return sAlias;
				}
			}
		}
		return null;
	}
	catch (KeyStoreException ex)
	{
		throw new CryptoException(RB.getString("NoMatchCertificate.exception.message"), ex);
	}
}
 
Example #4
Source File: Cryptography.java    From zap-android with MIT License 6 votes vote down vote up
private byte[] rsaEncryptKey(byte[] secret) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException, NoSuchPaddingException, UnrecoverableEntryException, InvalidKeyException {

        KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE_NAME);
        keyStore.load(null);

        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ENCRYPTION, null);
        Cipher inputCipher = Cipher.getInstance(RSA_MODE, CIPHER_PROVIDER_NAME_ENCRYPTION_DECRYPTION_RSA);
        inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher);
        cipherOutputStream.write(secret);
        cipherOutputStream.close();

        byte[] encryptedKeyAsByteArray = outputStream.toByteArray();
        return encryptedKeyAsByteArray;
    }
 
Example #5
Source File: X509KeySelectorTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test()
public void select_publicKey_exception() throws Exception {
    // given
    selector = spy(new X509KeySelector(keystore));
    KeyInfo keyinfo = mock(KeyInfo.class);
    ArrayList<XMLStructure> list = new ArrayList<XMLStructure>();
    X509Data x509Data = mock(X509Data.class);
    list.add(x509Data);
    doReturn(list).when(keyinfo).getContent();
    ArrayList<Object> x509DataContent = new ArrayList<Object>();
    x509DataContent.add(mock(X509Certificate.class));
    doReturn(x509DataContent).when(x509Data).getContent();
    doThrow(new KeyStoreException("key exception")).when(selector)
            .getPublicKeyFromKeystore(any(X509Certificate.class),
                    any(SignatureMethod.class));

    // when
    try {
        selector.select(keyinfo, null, null, null);
        fail();
    } catch (KeySelectorException e) {
        assertTrue(e.getCause().getMessage().contains("key exception"));
    }
}
 
Example #6
Source File: KeyStoreResolver.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor KeyStoreIterator
 *
 * @param keyStore
 */
public KeyStoreIterator(KeyStore keyStore) {
    try {
        this.keyStore = keyStore;
        this.aliases = this.keyStore.aliases();
    } catch (KeyStoreException ex) {
        // empty Enumeration
        this.aliases = new Enumeration<String>() {
            public boolean hasMoreElements() {
                return false;
            }
            public String nextElement() {
                return null;
            }
        };
    }
}
 
Example #7
Source File: KeyStore.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the certificate chain for the keystore entry.
 */
void setCertificateChain(X509Certificate[] chain)
    throws CertificateException, KeyStoreException
{
    for (int i = 0; i < chain.length; i++) {
        byte[] encoding = chain[i].getEncoded();
        if (i == 0 && privateKey != null) {
            storeCertificate(getName(), alias, encoding,
                encoding.length, privateKey.getHCryptProvider(),
                privateKey.getHCryptKey());

        } else {
            storeCertificate(getName(), alias, encoding,
                encoding.length, 0L, 0L); // no private key to attach
        }
    }
    certChain = chain;
}
 
Example #8
Source File: KeyStoreHelperTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private SecretKey storeKeyIntoKeyStoreFile(final String keyPhrase)
        throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException,
        InvalidKeyException, InvalidKeySpecException {
    final KeyStore keyStore = KeyStore.getInstance("JCEKS");
    keyStore.load(null, KEYSTORE_SERVER_PASSWORD.toCharArray());

    final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
    final SecretKey mySecretKey = secretKeyFactory.generateSecret(new DESKeySpec(keyPhrase.getBytes()));
    final KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(mySecretKey);
    keyStore.setEntry(KEY_ALIAS, skEntry, new KeyStore.PasswordProtection(KEY_PASSWORD.toCharArray()));

    try (FileOutputStream fos = new java.io.FileOutputStream(KEYSTORE_JCEKS_FILENAME, false)) {
        keyStore.store(fos, KEYSTORE_SERVER_PASSWORD.toCharArray());
    }
    return mySecretKey;
}
 
Example #9
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
public static CloseableHttpAsyncClient getInstance(ServerConfig serverConfig)
	throws IOException{
	if (HTTPC_CLIENT == null) {
		if (serverConfig.isTrustAllCertificates()) {
			try {
				SSLContext sslContext = SSLContexts.custom()
					.loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();
				HTTPC_CLIENT = HttpAsyncClients.custom()
					.setSSLHostnameVerifier((NoopHostnameVerifier.INSTANCE))
					.setSSLContext(sslContext)
					.build();
			} catch (KeyManagementException | NoSuchAlgorithmException
					| KeyStoreException e) {
				throw new IOException(e);
			} 
			
		} else {
			HTTPC_CLIENT = HttpAsyncClients.createDefault();
		}
		
		HTTPC_CLIENT.start();
	}
	return HTTPC_CLIENT;
}
 
Example #10
Source File: SecurityUtils.java    From RISE-V2G with MIT License 6 votes vote down vote up
/**
 * Returns a standard keystore which holds the respective credentials (private key and certificate chain).
 * 
 * @param keyStoreIS The input stream of the keystore
 * @param keyStorePassword The password which protects the keystore
 * @param keyStoreType The type of the keystore, either "jks" or "pkcs12"
 * @return The respective keystore
 */
private static KeyStore getKeyStore(InputStream keyStoreIS, String keyStorePassword, String keyStoreType) {
	KeyStore keyStore = null;
	
	try {
		keyStore = KeyStore.getInstance(keyStoreType);
		keyStore.load(keyStoreIS, keyStorePassword.toCharArray());
		keyStoreIS.close();
		return keyStore;
	} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | 
			IOException | NullPointerException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to load keystore", e);
	} 
	
	return null;
}
 
Example #11
Source File: CxfSecureRsExampleTest.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
private static void assertGreet(String uri, String user, String password, int responseCode,
        String responseBody) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, CertificateException, IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpGet request = new HttpGet(uri + "/Joe");
        request.setHeader("Content-Type", "application/json");
        if (user != null) {
            String auth = user + ":" + password;
            String authHeader = "Basic "
                    + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.ISO_8859_1));
            request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        }
        try (CloseableHttpResponse response = httpclient.execute(request)) {
            final int actualCode = response.getStatusLine().getStatusCode();
            Assert.assertEquals(responseCode, actualCode);
            if (actualCode == 200) {
                HttpEntity entity = response.getEntity();
                String body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                Assert.assertTrue(body.startsWith(responseBody));
            }
        }
    }
}
 
Example #12
Source File: ReportServer.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
public void start(int pPort) throws IOException {
    if (sslWorkerThread == null) {
        //keystore including the key for HTTPs connection
        String ksName = "dsworkbench.jks";
        char ksPass[] = "dsworkbench".toCharArray();
        char ctPass[] = "dsworkbench".toCharArray();
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(ksName), ksPass);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, ctPass);
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(kmf.getKeyManagers(), null, null);
            SSLServerSocketFactory ssf = sc.getServerSocketFactory();
            SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(pPort);
            s.setEnabledCipherSuites(sc.getServerSocketFactory().getSupportedCipherSuites());
            sslWorkerThread = new SSLWorkerThread(s);
            sslWorkerThread.start();
        } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | KeyManagementException | UnrecoverableKeyException ex) {
            logger.error("Failed to decrypt SSL key.", ex);
        }
    } else {
        logger.info("Server is already running");
    }
}
 
Example #13
Source File: PFSecurityUtilsOld.java    From PFLockScreen-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Load AndroidKeyStore.
 * @return true if keystore loaded successfully
 */
private KeyStore loadKeyStore() throws PFSecurityException {
    try {
        final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        return keyStore;
    } catch (KeyStoreException
            | NoSuchAlgorithmException
            | CertificateException
            | IOException e) {
        e.printStackTrace();
        throw new PFSecurityException(
                "Can not load keystore:" + e.getMessage(),
                PFSecurityUtilsErrorCodes.ERROR_LOAD_KEY_STORE
        );
    }
}
 
Example #14
Source File: PKCS12KeyStore.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Deletes the entry identified by the given alias from this keystore.
 *
 * @param alias the alias name
 *
 * @exception KeyStoreException if the entry cannot be removed.
 */
public synchronized void engineDeleteEntry(String alias)
    throws KeyStoreException
{
    if (debug != null) {
        debug.println("Removing entry at alias '" + alias + "'");
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (entry instanceof PrivateKeyEntry) {
        PrivateKeyEntry keyEntry = (PrivateKeyEntry) entry;
        if (keyEntry.chain != null) {
            certificateCount -= keyEntry.chain.length;
        }
        privateKeyCount--;
    } else if (entry instanceof CertEntry) {
        certificateCount--;
    } else if (entry instanceof SecretKeyEntry) {
        secretKeyCount--;
    }
    entries.remove(alias.toLowerCase(Locale.ENGLISH));
}
 
Example #15
Source File: RabbitMQContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
private SSLContext createSslContext(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword)
    throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException
{
    ClassLoader classLoader = getClass().getClassLoader();

    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(new File(classLoader.getResource(keystoreFile).getFile())), keystorePassword.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, "password".toCharArray());

    KeyStore trustStore = KeyStore.getInstance("PKCS12");
    trustStore.load(new FileInputStream(new File(classLoader.getResource(truststoreFile).getFile())), truststorePassword.toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(trustStore);

    SSLContext c = SSLContext.getInstance("TLSv1.2");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return c;
}
 
Example #16
Source File: AbstractSpreadSheetDocumentRecordWriter.java    From hadoopoffice with Apache License 2.0 6 votes vote down vote up
/***
 * Reads the  (private) key and certificate from keystore to sign
 * 
 * @param conf
 * @throws OfficeWriterException
 * @throws IOException
 */
private void readSigningKeyAndCertificate(Configuration conf) 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");
		HadoopKeyStoreManager hksm = new HadoopKeyStoreManager(conf);
		try {
			hksm.openKeyStore(new Path(this.howc.getSigKeystoreFile()), this.howc.getSigKeystoreType(), this.howc.getSigKeystorePassword());
			this.howc.setSigKey(hksm.getPrivateKey(this.howc.getSigKeystoreAlias(), this.howc.getSigKeystorePassword()));
			this.howc.setSigCertificate((X509Certificate) hksm.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 #17
Source File: BurpClientIT.java    From burp-rest-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testGetProxyHistoryAndSiteMap() throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    HttpMessageList proxyHistory = burpClient.getProxyHistory();
    assertEquals(0, proxyHistory.getHttpMessages().size());

    String urlString = "http://www.vmware.com";

    HttpMessageList siteMap = burpClient.getSiteMap(urlString);
    assertEquals(0, siteMap.getHttpMessages().size());

    sendRequestThruProxy();

    proxyHistory = burpClient.getProxyHistory();
    assertNotEquals(0, proxyHistory.getHttpMessages().size());

    siteMap = burpClient.getSiteMap(urlString);
    assertNotEquals(0, siteMap.getHttpMessages().size());
}
 
Example #18
Source File: WebhookService.java    From webanno with Apache License 2.0 6 votes vote down vote up
public WebhookService()
    throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException
{
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain,
            String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy).build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

    nonValidatingRequestFactory = new HttpComponentsClientHttpRequestFactory();
    nonValidatingRequestFactory.setHttpClient(httpClient);
}
 
Example #19
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * This method creates an insecure SSL factory that will trust on self signed certificates.
 * For that we use {@link TrustSelfSignedStrategy}.
 */
protected SSLConnectionSocketFactory createInsecureSslFactory() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(new TrustSelfSignedStrategy());
        SSLContext sc = builder.build();

        if (acceptAllKindsOfCertificates) {
            TrustManager[] trustAllCerts = new TrustManager[1];
            TrustManager tm = new TrustAllManager();
            trustAllCerts[0] = tm;
            sc.init(null, trustAllCerts, null);

            HostnameVerifier hostnameVerifier = createInsecureHostNameVerifier();
            return new SSLConnectionSocketFactory(sc, hostnameVerifier);
        }
        return new SSLConnectionSocketFactory(sc);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new ApacheCloudStackClientRuntimeException(e);
    }
}
 
Example #20
Source File: SignerParams.java    From Xpatch with Apache License 2.0 6 votes vote down vote up
private static Key getKeyStoreKey(KeyStore ks, String keyAlias, List<char[]> passwords)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    UnrecoverableKeyException lastFailure = null;
    for (char[] password : passwords) {
        try {
            return ks.getKey(keyAlias, password);
        } catch (UnrecoverableKeyException e) {
            lastFailure = e;
        }
    }
    if (lastFailure == null) {
        throw new RuntimeException("No key passwords");
    } else {
        throw lastFailure;
    }
}
 
Example #21
Source File: GetHTTP.java    From localization_nifi with 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 #22
Source File: CertificateLoaderImpl.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * When a PIN(Personal Identification Number) and Alias was informed, 
 * obtain the certificate from a Token or Smartcard, defined by ICP-BRASIL with the name A3.
 *
 * @param pinNumber a PIN(Personal Identification Number)
 * @param alias desired alias
 * @return  the certificate information in X509Certificate format
 * 
 */
 @Override
public X509Certificate loadFromToken(String pinNumber, String alias) {
    if (this.keyStore == null) {
        KeyStoreLoader keyStoreLoader = KeyStoreLoaderFactory.factoryKeyStoreLoader();
        this.keyStore = keyStoreLoader.getKeyStore();
    }
    try {
        return (X509Certificate) this.keyStore.getCertificateChain(alias)[0];
    } catch (KeyStoreException e) {
        throw new CertificateCoreException("", e);
    }
}
 
Example #23
Source File: PrivateKeyResolver.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private PrivateKey resolveX509Certificate(
    XMLX509Certificate x509Cert
) throws XMLSecurityException, KeyStoreException {
    log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?");
    byte[] x509CertBytes = x509Cert.getCertificateBytes();

    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {

            Certificate cert = keyStore.getCertificate(alias);
            if (cert instanceof X509Certificate) {
                byte[] certBytes = null;

                try {
                    certBytes = cert.getEncoded();
                } catch (CertificateEncodingException e1) {
                }

                if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) {
                    log.log(java.util.logging.Level.FINE, "match !!! ");

                    try {
                        Key key = keyStore.getKey(alias, password);
                        if (key instanceof PrivateKey) {
                            return (PrivateKey) key;
                        }
                    }
                    catch (Exception e) {
                        log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
                        // Keep searching
                    }
                }
            }
        }
    }

    return null;
}
 
Example #24
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void createTrustStore() throws CryptoException {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        setTrustStore(keyStore);
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | InvalidArgumentException e) {
        throw new CryptoException("Cannot create trust store. Error: " + e.getMessage(), e);
    }
}
 
Example #25
Source File: CipherTestUtils.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public AlwaysTrustManager(KeyStore keyStore)
        throws NoSuchAlgorithmException, KeyStoreException {

    TrustManagerFactory tmf
            = TrustManagerFactory.getInstance(TrustManagerFactory.
                    getDefaultAlgorithm());
    tmf.init(keyStore);

    TrustManager tms[] = tmf.getTrustManagers();
    for (TrustManager tm : tms) {
        trustManager = (X509TrustManager) tm;
        return;
    }

}
 
Example #26
Source File: ServerSecurityProducer.java    From datawave with Apache License 2.0 5 votes vote down vote up
private SubjectIssuerDNPair lookupServerDN() throws KeyStoreException {
    if (domain == null) {
        throw new IllegalArgumentException("Unable to find security domain.");
    }
    
    KeyStore keystore = domain.getKeyStore();
    final X509Certificate cert = (X509Certificate) keystore.getCertificate(keystore.aliases().nextElement());
    final String serverDN = cert.getSubjectX500Principal().getName();
    final String serverIssuerDN = cert.getIssuerX500Principal().getName();
    return SubjectIssuerDNPair.of(serverDN, serverIssuerDN);
}
 
Example #27
Source File: CertificateAuthorityCli.java    From protect with MIT License 5 votes vote down vote up
public static void main(final String args[]) throws IOException, CertificateException, NoSuchAlgorithmException,
		InvalidKeySpecException, KeyStoreException {

	Security.addProvider(new BouncyCastleProvider());
	Security.addProvider(new EdDSASecurityProvider());

	// Check usage
	if (args.length < 4) {
		System.err.println("USAGE: ca-path key-path cert-path [servers=true/false]");
		System.exit(1);
	}

	// Get directories from arguments
	final File caPath = new File(args[0]);
	final File keyPath = new File(args[1]);
	final File certPath = new File(args[2]);
	final boolean areServers = Boolean.parseBoolean(args[3]);

	if (areServers) {
		// Generate Server Certificates using server configuration
		// These IP addresses will have subject alternative names
		issueServerCertificates(caPath, keyPath, certPath);
	} else {
		// Generate Client Certificates using client configuration
		// These certificates will all be issued by the same client CA
		issueClientCertificates(caPath, keyPath, certPath);
	}

}
 
Example #28
Source File: CertificateHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static byte[] buildAndSaveKeystore(final String alias, final String cert, final String privateKey, final String storePassword) throws KeyStoreException, CertificateException,
NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(alias), "Certificate alias cannot be blank");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(cert), "Certificate cannot be blank");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(privateKey), "Private key cannot be blank");

    final KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword);

    try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
        return os.toByteArray();
    }
}
 
Example #29
Source File: DefaultCryptoService.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify(String algorithm, String signed, byte[] signature) {
  boolean verified = false;
  try {
    Signature sig=Signature.getInstance(algorithm);
    sig.initVerify(ks.getCertificateForGateway().getPublicKey());
    sig.update(signed.getBytes(StandardCharsets.UTF_8));
    verified = sig.verify(signature);
  } catch (SignatureException | KeystoreServiceException | InvalidKeyException | NoSuchAlgorithmException | KeyStoreException e) {
    LOG.failedToVerifySignature( e );
  }
  LOG.signatureVerified( verified );
  return verified;
}
 
Example #30
Source File: ReadCertStoreSampleUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static KeyPair getSampleKeyPair() throws CertificateException,
        NoSuchAlgorithmException, IOException, InvalidKeyException, KeyStoreException,
        NoSuchProviderException, SignatureException {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "SHA1WithRSA");
    SecureRandom random = SecureRandom.getInstance("RSA", "SHA1WithRSA");
    keyGen.initialize(1024, random);
    KeyPair keypair = keyGen.generateKeyPair();
    return keypair;
}