List of usage examples for java.security.cert CertificateFactory generateCertificate
public final Certificate generateCertificate(InputStream inStream) throws CertificateException
From source file:org.commonjava.maven.galley.transport.htcli.internal.SSLUtils.java
public static KeyStore readCerts(final String pemContent, final String aliasPrefix) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null);/* w w w .j av a 2 s . c o m*/ final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final List<String> lines = readLines(pemContent); final StringBuilder current = new StringBuilder(); final List<String> entries = new ArrayList<String>(); for (final String line : lines) { if (line == null) { continue; } if (line.startsWith("-----BEGIN")) { current.setLength(0); } else if (line.startsWith("-----END")) { entries.add(current.toString()); } else { current.append(line.trim()); } } int i = 0; for (final String entry : entries) { final byte[] data = decodeBase64(entry); final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data)); ks.setCertificateEntry(aliasPrefix + i, c); i++; } return ks; }
From source file:org.wso2.emm.agent.utils.CommonUtils.java
/** * Generates keys, CSR and certificates for the devices. * @param context - Application context. * @param listener - DeviceCertCreationListener which provide device . *//*from www.jav a2s . c o m*/ public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener) throws AndroidAgentException { if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) { try { listener.onDeviceCertCreated( new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } else { try { ServerConfig utils = new ServerConfig(); final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE) .generateKeyPair(); X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject, deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate()); EndPointInfo endPointInfo = new EndPointInfo(); endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST); endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT); endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT)); new APIController().invokeAPI(endPointInfo, new APIResultCallBack() { @Override public void onReceiveAPIResult(Map<String, String> result, int requestCode) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(result.get("response"), Base64.DEFAULT)); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS, (Key) deviceKeyPair.getPrivate(), Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert }); keyStore.store(byteArrayOutputStream, Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray()); FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME, Context.MODE_PRIVATE); outputStream.write(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.close(); outputStream.close(); try { listener.onDeviceCertCreated(new BufferedInputStream( context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } catch (CertificateException e) { Log.e(TAG, e.getMessage()); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }, Constants.SCEP_REQUEST_CODE, context, true); } catch (NoSuchAlgorithmException e) { throw new AndroidAgentException("No algorithm for key generation", e); } catch (SignatureException e) { throw new AndroidAgentException("Invalid Signature", e); } catch (NoSuchProviderException e) { throw new AndroidAgentException("Invalid provider", e); } catch (InvalidKeyException e) { throw new AndroidAgentException("Invalid key", e); } } }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * @throws java.lang.Exception/* w w w.j a v a 2s . co m*/ */ @BeforeClass public static void setUpBeforeClass() throws Exception { // Just in case, add the BouncyCastle provider // It gets added from the CredentialManagerImpl constructor as well // but we may need some crypto operations before we invoke the Cred. Manager Security.addProvider(new BouncyCastleProvider()); // Create a test username and password for a service serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; }
From source file:com.vmware.identity.idm.server.ServerUtils.java
private static X509Certificate getCert(LdapValue value) { X509Certificate cert = null;/*from www .j a v a 2 s. co m*/ if (value != null) { byte[] certBytes = value.getValue(); if (certBytes != null) { try { ByteArrayInputStream inpstream = new ByteArrayInputStream(certBytes); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inpstream); } catch (CertificateException e) { throw new RuntimeException("Failed to generate certificate"); } } } return cert; }
From source file:com.vmware.bdd.manager.SoftwareManagerCollector.java
/** * TODO this method has to be reverted://w w w. j av a 2s . co m * because if the target path is not accessible, it will load cert from the default keystore in java home, * but still try to write it to the non accessible path. * @param certificate * @param keyStorePath */ protected static void saveSslCertificate(String certificate, String keyStorePath) { Certificate[] certs; //parse certificates try { if (CommonUtil.isBlank(certificate)) { throw SoftwareManagerCollectorException.BAD_CERT(null); } byte[] certBytes = Base64.decodeBase64(certificate.replaceAll("-----BEGIN CERTIFICATE-----", "") .replaceAll("-----END CERTIFICATE-----", "").getBytes()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection c = cf.generateCertificates(new ByteArrayInputStream(certBytes)); certs = new Certificate[c.toArray().length]; if (c.size() == 0) { throw SoftwareManagerCollectorException.BAD_CERT(null); } else if (c.size() == 1) { certs[0] = cf.generateCertificate(new ByteArrayInputStream(certBytes)); } else { certs = (Certificate[]) c.toArray(certs); } } catch (CertificateException e) { throw SoftwareManagerCollectorException.BAD_CERT(e); } //load & save keystore OutputStream out = null; try { KeyStore keyStore = CommonUtil.loadAppMgrKeyStore(keyStorePath); if (keyStore == null) { logger.error(Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE")); throw new SWMgrCollectorInternalException( Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE")); } MessageDigest md5 = MessageDigest.getInstance("MD5"); String md5Fingerprint = ""; for (Certificate cert : certs) { md5.update(cert.getEncoded()); md5Fingerprint = CommonUtil.toHexString(md5.digest()); logger.debug("md5 finger print: " + md5Fingerprint); logger.debug("added cert: " + cert); keyStore.setCertificateEntry(md5Fingerprint, cert); } out = new FileOutputStream(keyStorePath + Constants.APPMANAGER_KEYSTORE_FILE); keyStore.store(new BufferedOutputStream(out), Constants.APPMANAGER_KEYSTORE_PASSWORD); } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) { logger.error(Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"), e); throw new SWMgrCollectorInternalException(e, Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT")); } finally { if (out != null) { try { out.close(); } catch (IOException e) { logger.warn("Output stream of appmanagers.jks close failed."); } } } }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * @throws java.lang.Exception//from www . j a v a 2s . co m */ @BeforeClass public static void setUpBeforeClass() throws Exception { // Just in case, add the BouncyCastle provider // It gets added from the CredentialManagerImpl constructor as well // but we may need some crypto operations before we invoke the Cred. Manager Security.addProvider(new BouncyCastleProvider()); // Create a test username and password for a service serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; }
From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java
/** * Convert the supplied certificate object into an X509Certificate object. * * @param certIn/* w ww . java 2s. c om*/ * The Certificate object * @return The converted X509Certificate object * @throws CryptoException * A problem occurred during the conversion */ public static X509Certificate convertCertificate(Certificate certIn) throws CryptoException { try { CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce()); ByteArrayInputStream bais = new ByteArrayInputStream(certIn.getEncoded()); return (X509Certificate) cf.generateCertificate(bais); } catch (CertificateException e) { throw new CryptoException(res.getString("NoConvertCertificate.exception.message"), e); } catch (NoSuchProviderException e) { throw new CryptoException(res.getString("NoConvertCertificate.exception.message"), e); } }
From source file:at.alladin.rmbt.client.RMBTClient.java
public static SSLContext getSSLContext(final String caResource, final String certResource) throws NoSuchAlgorithmException, KeyManagementException { X509Certificate _ca = null;/*from w ww. j av a 2 s .c om*/ try { if (caResource != null) { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); _ca = (X509Certificate) cf .generateCertificate(RMBTClient.class.getClassLoader().getResourceAsStream(caResource)); } } catch (final Exception e) { e.printStackTrace(); } final X509Certificate ca = _ca; X509Certificate _cert = null; try { if (certResource != null) { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); _cert = (X509Certificate) cf .generateCertificate(RMBTClient.class.getClassLoader().getResourceAsStream(certResource)); } } catch (final Exception e) { e.printStackTrace(); } final X509Certificate cert = _cert; // TrustManagerFactory tmf = null; // try // { // if (cert != null) // { // final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // ks.load(null, null); // ks.setCertificateEntry("crt", cert); // // tmf = // TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(ks); // } // } // catch (Exception e) // { // e.printStackTrace(); // } final TrustManager tm; if (cert == null) tm = getTrustingManager(); else tm = new javax.net.ssl.X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { // System.out.println("getAcceptedIssuers"); if (ca == null) return new X509Certificate[] { cert }; else return new X509Certificate[] { ca }; } public void checkClientTrusted(final X509Certificate[] certs, final String authType) throws CertificateException { // System.out.println("checkClientTrusted: " + // Arrays.toString(certs) + " - " + authType); } public void checkServerTrusted(final X509Certificate[] certs, final String authType) throws CertificateException { // System.out.println("checkServerTrusted: " + // Arrays.toString(certs) + " - " + authType); if (certs == null) throw new CertificateException(); for (final X509Certificate c : certs) if (cert.equals(c)) return; throw new CertificateException(); } }; final TrustManager[] trustManagers = new TrustManager[] { tm }; javax.net.ssl.SSLContext sc; sc = javax.net.ssl.SSLContext.getInstance(Config.RMBT_ENCRYPTION_STRING); sc.init(null, trustManagers, new java.security.SecureRandom()); return sc; }
From source file:org.wso2.iot.agent.utils.CommonUtils.java
/** * Generates keys, CSR and certificates for the devices. * @param context - Application context. * @param listener - DeviceCertCreationListener which provide device . *///w w w .j ava 2 s . c om public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener) throws AndroidAgentException { if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) { try { listener.onDeviceCertCreated( new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } else { try { ServerConfig utils = new ServerConfig(); final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE) .generateKeyPair(); X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject, deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate()); EndPointInfo endPointInfo = new EndPointInfo(); endPointInfo.setHttpMethod(org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS.POST); endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT); endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT)); new APIController().invokeAPI(endPointInfo, new APIResultCallBack() { @Override public void onReceiveAPIResult(Map<String, String> result, int requestCode) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(result.get("response"), Base64.DEFAULT)); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS, (Key) deviceKeyPair.getPrivate(), Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert }); keyStore.store(byteArrayOutputStream, Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray()); FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME, Context.MODE_PRIVATE); outputStream.write(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.close(); outputStream.close(); try { listener.onDeviceCertCreated(new BufferedInputStream( context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException e) { Log.e(TAG, e.getMessage(), e); } } }, Constants.SCEP_REQUEST_CODE, context, true); } catch (NoSuchAlgorithmException e) { throw new AndroidAgentException("No algorithm for key generation", e); } catch (SignatureException e) { throw new AndroidAgentException("Invalid Signature", e); } catch (NoSuchProviderException e) { throw new AndroidAgentException("Invalid provider", e); } catch (InvalidKeyException e) { throw new AndroidAgentException("Invalid key", e); } } }
From source file:nl.surfnet.spring.security.opensaml.CertificateStoreImpl.java
private void appendToKeyStore(String keyAlias, String pemCert) throws Exception { String wrappedCert = "-----BEGIN CERTIFICATE-----\n" + pemCert + "\n-----END CERTIFICATE-----"; ByteArrayInputStream certificateInputStream = new ByteArrayInputStream(wrappedCert.getBytes()); final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); final Certificate cert = certificateFactory.generateCertificate(certificateInputStream); IOUtils.closeQuietly(certificateInputStream); keyStore.setCertificateEntry(keyAlias, cert); }