List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:org.freebxml.omar.server.security.authentication.AuthenticationServiceImpl.java
protected void registerUserCertificate(String userId, X509Certificate cert) throws RegistryException { java.io.FileOutputStream fos = null; try {// www . ja va2 s. c o m KeyStore keyStore = getKeyStore(); //Make sure no other user is registered with same cert under a different alias String alias = getKeyStore().getCertificateAlias(cert); if ((null != alias) && (!userId.equalsIgnoreCase(alias))) { throw new UserRegistrationException(ServerResourceBundle.getInstance() .getString("message.error.certificateAlreadyExists", new Object[] { userId, alias })); } // Check if already in store X509Certificate oldCert = null; try { oldCert = getCertificate(userId); } catch (Exception e) { } //System.err.println("Checking the certificates are the same..."); if ((oldCert != null) && !certificatesAreSame(cert, oldCert)) { throw new UserRegistrationException(ServerResourceBundle.getInstance() .getString("message.userRegistrationFailed", new Object[] { userId })); } //Add the cert. to the keystore if the cert. does not exist yet if (oldCert == null) { if (propsReader.getProperty("omar.security.validateCertificates").trim().equalsIgnoreCase("true")) { validateCertificate(cert); } synchronized (keyStoreWriteLock) { keyStore.setCertificateEntry(userId, cert); String keystoreFile = getKeyStoreFileName(); fos = new java.io.FileOutputStream(keystoreFile); String keystorePass = getKeyStorePassword(); keyStore.store(fos, keystorePass.toCharArray()); fos.flush(); fos.close(); this.keyStore = null; //Update publicKeyToCertMap publicKeyToCertMap.put(cert.getPublicKey(), cert); } } } catch (KeyStoreException e) { throw new UserRegistrationException(e); } catch (IOException e) { throw new UserRegistrationException(e); } catch (java.security.cert.CertificateException e) { throw new UserRegistrationException(e); } catch (NoSuchAlgorithmException e) { throw new UserRegistrationException(e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:it.cnr.icar.eric.server.security.authentication.AuthenticationServiceImpl.java
protected void registerUserCertificate(String userId, X509Certificate cert) throws RegistryException { java.io.FileOutputStream fos = null; try {//w w w . j a va 2 s . c om KeyStore keyStore = getKeyStore(); // Make sure no other user is registered with same cert under a // different alias String alias = getKeyStore().getCertificateAlias(cert); if ((null != alias) && (!userId.equalsIgnoreCase(alias))) { throw new UserRegistrationException(ServerResourceBundle.getInstance() .getString("message.error.certificateAlreadyExists", new Object[] { userId, alias })); } // Check if already in store X509Certificate oldCert = null; try { oldCert = getCertificate(userId); } catch (Exception e) { } // System.err.println("Checking the certificates are the same..."); if ((oldCert != null) && !certificatesAreSame(cert, oldCert)) { throw new UserRegistrationException(ServerResourceBundle.getInstance() .getString("message.userRegistrationFailed", new Object[] { userId })); } // Add the cert. to the keystore if the cert. does not exist yet if (oldCert == null) { if (propsReader.getProperty("eric.security.validateCertificates").trim().equalsIgnoreCase("true")) { validateCertificate(cert); } synchronized (keyStoreWriteLock) { keyStore.setCertificateEntry(userId, cert); String keystoreFile = getKeyStoreFileName(); fos = new java.io.FileOutputStream(keystoreFile); String keystorePass = getKeyStorePassword(); keyStore.store(fos, keystorePass.toCharArray()); fos.flush(); fos.close(); this.keyStore = null; // Update publicKeyToCertMap publicKeyToCertMap.put(cert.getPublicKey(), cert); } } } catch (KeyStoreException e) { throw new UserRegistrationException(e); } catch (IOException e) { throw new UserRegistrationException(e); } catch (java.security.cert.CertificateException e) { throw new UserRegistrationException(e); } catch (NoSuchAlgorithmException e) { throw new UserRegistrationException(e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:org.lockss.util.KeyStoreUtil.java
private static void initializeKeyStore(KeyStore keyStore, String domainName, String password) throws IOException, CertificateException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException { String keyAlias = domainName + keySuffix; String certAlias = domainName + crtSuffix; String keyStorePassword = domainName; String keyStoreFileName = domainName + ".jceks"; File keyStoreFile = new File(keyStoreFileName); if (keyStoreFile.exists()) { log.debug("Key store file " + keyStoreFileName + " exists"); throw new IOException("Key store file " + keyStoreFileName + " exists"); }//from www.ja v a2s .c om String keyAlgName = "RSA"; String sigAlgName = "MD5WithRSA"; log.debug("About to create a CertAndKeyGen: " + keyAlgName + " " + sigAlgName); CertAndKeyGen keypair; try { keypair = new CertAndKeyGen(keyAlgName, sigAlgName); } catch (NoSuchAlgorithmException e) { log.debug("new CertAndKeyGen(" + keyAlgName + "," + sigAlgName + ") threw " + e); throw e; } log.debug("About to generate a key pair"); try { keypair.generate(1024); } catch (InvalidKeyException e) { log.debug("keypair.generate(1024) threw " + e); throw e; } log.debug("About to get a PrivateKey"); PrivateKey privKey = keypair.getPrivateKey(); log.debug("MyKey: " + privKey.getAlgorithm() + " " + privKey.getFormat()); log.debug("About to get a self-signed certificate"); X509Certificate[] chain = new X509Certificate[1]; X500Name x500Name = new X500Name( "CN=" + domainName + ", " + "OU=LOCKSS Team, O=Stanford, " + "L=Stanford, S=California, C=US"); chain[0] = keypair.getSelfCertificate(x500Name, 365 * 24 * 60 * 60); log.debug("Certificate: " + chain[0].toString()); log.debug("About to keyStore.load(null)"); try { keyStore.load(null, keyStorePassword.toCharArray()); } catch (IOException e) { log.debug("keyStore.load() threw " + e); throw e; } catch (CertificateException e) { log.debug("keyStore.load() threw " + e); throw e; } catch (NoSuchAlgorithmException e) { log.debug("keyStore.load() threw " + e); throw e; } log.debug("About to store " + certAlias + " in key store"); try { keyStore.setCertificateEntry(certAlias, chain[0]); } catch (KeyStoreException e) { log.debug("keyStore.setCertificateEntry() threw " + e); throw e; } log.debug("About to store " + keyAlias + " in key store"); try { keyStore.setKeyEntry(keyAlias, privKey, password.toCharArray(), chain); } catch (KeyStoreException e) { log.debug("keyStore.setKeyEntry() threw " + e); throw e; } log.debug("About to getKeyEntry()"); Key myKey = keyStore.getKey(keyAlias, password.toCharArray()); log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat()); log.debug("Done storing"); }
From source file:com.vmware.identity.openidconnect.client.AuthenticationFrameworkHelper.java
public void populateSSLCertificates(KeyStore keyStore) throws OIDCClientException, SSLConnectionException, AdminServerException { HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.GET, this.authenticationFrameworkSSLCertificateURL); HTTPResponse httpResponse = null;//from ww w .j a va2s. c om SSLContext sslContext; try { sslContext = SSLContext.getInstance("TLS"); TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new OIDCClientException("Failed to build SSL context: " + e.getMessage(), e); } httpResponse = OIDCClientUtils.sendSecureRequest(httpRequest, sslContext); try { if (httpResponse.getStatusCode() != 200 && httpResponse.getStatusCode() != 204) { throw AdminServerHelper.convertToAdminServerException(httpResponse.getStatusCode(), httpResponse.getContentAsJSONObject()); } } catch (ParseException e) { throw new OIDCClientException("Exception caught during exception conversion: " + e.getMessage(), e); } JSONArray jsonArray = (JSONArray) JSONValue.parse(httpResponse.getContent()); int index = 1; for (Object object : jsonArray) { JSONObject jsonObject = (JSONObject) object; String cert = (String) jsonObject.get("encoded"); cert = cert.replaceAll(X509Factory.BEGIN_CERT, "").replaceAll(X509Factory.END_CERT, ""); try { keyStore.setCertificateEntry(String.format("VecsSSLCert%d", index), convertToX509Certificate(cert)); } catch (KeyStoreException e) { throw new OIDCClientException("Failed to set X509 certificate in key store: " + e.getMessage(), e); } index++; } }
From source file:com.cloud.bridge.service.EC2RestServlet.java
/** * The SOAP API for EC2 uses WS-Security to sign all client requests. This requires that * the client have a public/private key pair and the public key defined by a X509 certificate. * Thus in order for a Cloud.com account holder to use the EC2's SOAP API he must register * his X509 certificate with the EC2 service. This function allows the Cloud.com account * holder to "load" his X509 certificate into the service. Note, that the SetUserKeys REST * function must be called before this call. * /*from w w w. j a va 2 s . c o m*/ * This is an authenticated REST call and as such must contain all the required REST parameters * including: Signature, Timestamp, Expires, etc. The signature is calculated using the * Cloud.com account holder's API access and secret keys and the Amazon defined EC2 signature * algorithm. * * A user can call this REST function any number of times, on each call the X509 certificate * simply over writes any previously stored value. */ private void setCertificate(HttpServletRequest request, HttpServletResponse response) throws Exception { Transaction txn = null; try { // [A] Pull the cert and cloud AccessKey from the request String[] certificate = request.getParameterValues("cert"); if (null == certificate || 0 == certificate.length) { response.sendError(530, "Missing cert parameter"); return; } // logger.debug( "SetCertificate cert: [" + certificate[0] + "]" ); String[] accessKey = request.getParameterValues("AWSAccessKeyId"); if (null == accessKey || 0 == accessKey.length) { response.sendError(530, "Missing AWSAccessKeyId parameter"); return; } // [B] Open our keystore FileInputStream fsIn = new FileInputStream(pathToKeystore); KeyStore certStore = KeyStore.getInstance("JKS"); certStore.load(fsIn, keystorePassword.toCharArray()); // -> use the Cloud API key to save the cert in the keystore // -> write the cert into the keystore on disk Certificate userCert = null; CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bs = new ByteArrayInputStream(certificate[0].getBytes()); while (bs.available() > 0) userCert = cf.generateCertificate(bs); certStore.setCertificateEntry(accessKey[0], userCert); FileOutputStream fsOut = new FileOutputStream(pathToKeystore); certStore.store(fsOut, keystorePassword.toCharArray()); // [C] Associate the cert's uniqueId with the Cloud API keys String uniqueId = AuthenticationUtils.X509CertUniqueId(userCert); logger.debug("SetCertificate, uniqueId: " + uniqueId); /* UserCredentialsDao credentialDao = new UserCredentialsDao(); credentialDao.setCertificateId( accessKey[0], uniqueId ); */ txn = Transaction.open(Transaction.AWSAPI_DB); UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]); user.setCertUniqueId(uniqueId); ucDao.update(user.getId(), user); response.setStatus(200); endResponse(response, "User certificate set successfully"); txn.commit(); } catch (NoSuchObjectException e) { logger.error("SetCertificate exception " + e.getMessage(), e); response.sendError(404, "SetCertificate exception " + e.getMessage()); } catch (Exception e) { logger.error("SetCertificate exception " + e.getMessage(), e); response.sendError(500, "SetCertificate exception " + e.getMessage()); } finally { txn.close(); } }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java
private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data, String type, String fileName, String path, String storepass, KeyStore store) throws KeystoreEditorException { OutputStream fos = null;//from w w w. ja va 2 s .co m try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) { if (StringUtils.isBlank(alias)) { throw new IllegalArgumentException("Alias cannot be null."); } Path storeFile = Paths.get(path); //check the two most common key/cert stores first (pkcs12 and jks) if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) { //priv key + cert chain KeyStore pkcs12Store = KeyStore.getInstance("PKCS12"); pkcs12Store.load(inputStream, storePassword.toCharArray()); Certificate[] chain = pkcs12Store.getCertificateChain(alias); Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray()); if (key != null) { store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain); fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); } } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) { //java keystore file KeyStore jks = KeyStore.getInstance("jks"); jks.load(inputStream, storePassword.toCharArray()); Enumeration<String> aliases = jks.aliases(); //we are going to store all entries from the jks regardless of the passed in alias while (aliases.hasMoreElements()) { String jksAlias = aliases.nextElement(); if (jks.isKeyEntry(jksAlias)) { Key key = jks.getKey(jksAlias, keyPassword.toCharArray()); Certificate[] certificateChain = jks.getCertificateChain(jksAlias); store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain); } else { Certificate certificate = jks.getCertificate(jksAlias); store.setCertificateEntry(jksAlias, certificate); } } fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); //need to parse der separately from pem, der has the same mime type but is binary hence checking both } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) { ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream); ASN1Primitive asn1Primitive = asn1InputStream.readObject(); X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; String cnStr = IETFUtils.valueToString(cn.getFirst().getValue()); if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) { store.setCertificateEntry(cnStr, certificate); } store.setCertificateEntry(alias, certificate); fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); //if it isn't one of the stores we support, it might be a key or cert by itself } else if (isPemParsable(type, fileName)) { //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); PEMParser pemParser = new PEMParser(reader); Object object; boolean setEntry = false; while ((object = pemParser.readObject()) != null) { if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) { PEMKeyPair pemKeyPair; if (object instanceof PEMEncryptedKeyPair) { PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object; JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder(); pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair( jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray())); } else { pemKeyPair = (PEMKeyPair) object; } KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair); PrivateKey privateKey = keyPair.getPrivate(); Certificate[] chain = store.getCertificateChain(alias); if (chain == null) { chain = buildCertChain(alias, store); } store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain); setEntry = true; } else if (object instanceof X509CertificateHolder) { X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object; CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate) .getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; String cnStr = IETFUtils.valueToString(cn.getFirst().getValue()); if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) { store.setCertificateEntry(cnStr, certificate); } store.setCertificateEntry(alias, certificate); setEntry = true; } else if (object instanceof ContentInfo) { ContentInfo contentInfo = (ContentInfo) object; if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) { CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo); OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure(); ASN1Set certificates = originatorInfo.getCertificates(); setEntry = importASN1CertificatesToStore(store, setEntry, certificates); } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) { SignedData signedData = SignedData.getInstance(contentInfo.getContent()); ASN1Set certificates = signedData.getCertificates(); setEntry = importASN1CertificatesToStore(store, setEntry, certificates); } } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) { PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object; Certificate[] chain = store.getCertificateChain(alias); if (chain == null) { chain = buildCertChain(alias, store); } try { store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain); setEntry = true; } catch (KeyStoreException keyEx) { try { PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(), keyPassword.toCharArray()); store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(), chain); setEntry = true; } catch (GeneralSecurityException e) { LOGGER.error( "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.", e); throw keyEx; } } } } if (setEntry) { fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); } } } catch (Exception e) { LOGGER.error("Unable to add entry {} to store", alias, e); throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException ignore) { } } } init(); }
From source file:be.fgov.kszbcss.rhq.websphere.connector.agent.ConnectorSubsystemComponent.java
public OperationResult invokeOperation(String name, Configuration parameters) throws InterruptedException, Exception { if (name.equals("importCertificateFromFile")) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream in = new FileInputStream(parameters.getSimple("file").getStringValue()); try {/*from w ww . ja va2 s .c o m*/ Iterator<? extends Certificate> it = cf.generateCertificates(in).iterator(); if (it.hasNext()) { TrustStoreManager.getInstance().addCertificate(parameters.getSimple("alias").getStringValue(), (X509Certificate) it.next()); } else { throw new Exception("No certificate found"); } } finally { in.close(); } return null; } else if (name.equals("retrieveCellCertificate")) { DeploymentManager dm = new DeploymentManager(null, new ConfigurationBasedProcessLocator(parameters)); String cell = dm.getCell(); ConfigQueryExecutor configQueryExecutor = ConfigQueryServiceFactory.getInstance() .getConfigQueryExecutor(dm); try { X509Certificate cert = configQueryExecutor.query(CellRootCertificateQuery.INSTANCE); TrustStoreManager.getInstance().addCertificate("cell:" + cell, cert); } finally { configQueryExecutor.destroy(); } return null; } else if (name.equals("retrieveCertificateFromPort")) { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(new KeyManager[0], new TrustManager[] { new AutoImportTrustManager(parameters.getSimple("alias").getStringValue()) }, new SecureRandom()); SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket( parameters.getSimple("host").getStringValue(), parameters.getSimple("port").getIntegerValue()); try { socket.startHandshake(); } finally { socket.close(); } return null; } else if (name.equals("listCertificates")) { final PropertyList certificates = new PropertyList("certificates"); TrustStoreManager.getInstance().execute(new TrustStoreAction() { public void execute(KeyStore truststore) throws Exception { // Sort the aliases for convenience Set<String> aliases = new TreeSet<String>(); for (Enumeration<String> e = truststore.aliases(); e.hasMoreElements();) { aliases.add(e.nextElement()); } for (String alias : aliases) { X509Certificate cert = (X509Certificate) truststore.getCertificate(alias); PropertyMap map = new PropertyMap("certificate"); map.put(new PropertySimple("alias", alias)); map.put(new PropertySimple("subject", cert.getSubjectDN().toString())); MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(cert.getEncoded()); byte[] digest = md.digest(); StringBuilder fingerprint = new StringBuilder(); for (int i = 0; i < digest.length; i++) { if (i > 0) { fingerprint.append(':'); } fingerprint.append(getHexDigit(((int) digest[i] & 0xf0) >> 4)); fingerprint.append(getHexDigit((int) digest[i] & 0x0f)); } map.put(new PropertySimple("fingerprint", fingerprint.toString())); certificates.add(map); } } }, true); if (log.isDebugEnabled()) { log.debug("certificates=" + certificates); } OperationResult result = new OperationResult(); result.getComplexResults().put(certificates); return result; } else if (name.equals("removeCertificate")) { final String alias = parameters.getSimple("alias").getStringValue(); TrustStoreManager.getInstance().execute(new TrustStoreAction() { public void execute(KeyStore truststore) throws Exception { truststore.deleteEntry(alias); } }, false); return null; } else if (name.equals("renameCertificate")) { final String oldAlias = parameters.getSimple("oldAlias").getStringValue(); final String newAlias = parameters.getSimple("newAlias").getStringValue(); TrustStoreManager.getInstance().execute(new TrustStoreAction() { public void execute(KeyStore truststore) throws Exception { Certificate cert = truststore.getCertificate(oldAlias); truststore.setCertificateEntry(newAlias, cert); truststore.deleteEntry(oldAlias); } }, false); return null; } else { return null; } }
From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java
/** * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int) *///from w w w .ja v a2s.c om public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException { final String methodName = ICertificateManager.CNAME + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", subjectData); DEBUGGER.debug("Value: {}", validityPeriod); DEBUGGER.debug("Value: {}", keySize); } final File rootDirectory = certConfig.getRootDirectory(); final String signatureAlgorithm = certConfig.getSignatureAlgorithm(); final String certificateAlgorithm = certConfig.getCertificateAlgorithm(); final File privateKeyDirectory = FileUtils .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0)); final File publicKeyDirectory = FileUtils .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0)); final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0)); final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0)); final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O=" + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C=" + subjectData.get(5) + ",E=" + subjectData.get(6)); if (DEBUG) { DEBUGGER.debug("rootDirectory: {}", rootDirectory); DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm); DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm); DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory); DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory); DEBUGGER.debug("csrDirectory: {}", csrDirectory); DEBUGGER.debug("storeDirectory: {}", storeDirectory); DEBUGGER.debug("x500Name: {}", x500Name); } File csrFile = null; JcaPEMWriter csrPemWriter = null; JcaPEMWriter publicKeyWriter = null; JcaPEMWriter privateKeyWriter = null; FileOutputStream csrFileStream = null; FileOutputStream keyStoreStream = null; FileOutputStream publicKeyFileStream = null; FileOutputStream privateKeyFileStream = null; OutputStreamWriter csrFileStreamWriter = null; OutputStreamWriter privateKeyStreamWriter = null; OutputStreamWriter publicKeyStreamWriter = null; try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, storePassword.toCharArray()); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } SecureRandom random = new SecureRandom(); KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm); keyGenerator.initialize(keySize, random); if (DEBUG) { DEBUGGER.debug("KeyGenerator: {}", keyGenerator); } KeyPair keyPair = keyGenerator.generateKeyPair(); if (DEBUG) { DEBUGGER.debug("KeyPair: {}", keyPair); } if (keyPair != null) { final Signature sig = Signature.getInstance(signatureAlgorithm); final PrivateKey privateKey = keyPair.getPrivate(); final PublicKey publicKey = keyPair.getPublic(); if (DEBUG) { DEBUGGER.debug("Signature: {}", sig); DEBUGGER.debug("PrivateKey: {}", privateKey); DEBUGGER.debug("PublicKey: {}", publicKey); } sig.initSign(privateKey, random); ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); if (DEBUG) { DEBUGGER.debug("ContentSigner: {}", signGen); } Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityPeriod); if (DEBUG) { DEBUGGER.debug("Calendar: {}", expiry); } CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType()); if (DEBUG) { DEBUGGER.debug("CertificateFactory: {}", certFactory); } X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) }; if (DEBUG) { DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert); } keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate( new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile())))); keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(), certFactory.generateCertificate(new FileInputStream( FileUtils.getFile(certConfig.getIntermediateCertificateFile())))); PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name, publicKey); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder); } PKCS10CertificationRequest csr = builder.build(signGen); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequest: {}", csr); } // write private key File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("privateKeyFile: {}", privateKeyFile); } if (!(privateKeyFile.createNewFile())) { throw new IOException("Failed to store private file"); } privateKeyFileStream = new FileOutputStream(privateKeyFile); privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream); if (DEBUG) { DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream); DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter); } privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter); privateKeyWriter.writeObject(privateKey); privateKeyWriter.flush(); privateKeyStreamWriter.flush(); privateKeyFileStream.flush(); // write public key File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PUBLICKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("publicKeyFile: {}", publicKeyFile); } if (!(publicKeyFile.createNewFile())) { throw new IOException("Failed to store public key file"); } publicKeyFileStream = new FileOutputStream(publicKeyFile); publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter); publicKeyWriter.writeObject(publicKey); publicKeyWriter.flush(); publicKeyStreamWriter.flush(); publicKeyFileStream.flush(); // write csr csrFile = FileUtils .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT); if (DEBUG) { DEBUGGER.debug("csrFile: {}", csrFile); } if (!(csrFile.createNewFile())) { throw new IOException("Failed to store CSR file"); } csrFileStream = new FileOutputStream(csrFile); csrFileStreamWriter = new OutputStreamWriter(csrFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } csrPemWriter = new JcaPEMWriter(csrFileStreamWriter); csrPemWriter.writeObject(csr); csrPemWriter.flush(); csrFileStreamWriter.flush(); csrFileStream.flush(); File keyStoreFile = FileUtils .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType()); if (DEBUG) { DEBUGGER.debug("keyStoreFile: {}", keyStoreFile); } keyStoreStream = FileUtils.openOutputStream(keyStoreFile); if (DEBUG) { DEBUGGER.debug("keyStoreStream: {}", keyStoreStream); } keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(), issuerCert); keyStore.store(keyStoreStream, storePassword.toCharArray()); keyStoreStream.flush(); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } } else { throw new CertificateManagementException("Failed to generate keypair. Cannot continue."); } } catch (FileNotFoundException fnfx) { throw new CertificateManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new CertificateManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new CertificateManagementException(nsax.getMessage(), nsax); } catch (IllegalStateException isx) { throw new CertificateManagementException(isx.getMessage(), isx); } catch (InvalidKeyException ikx) { throw new CertificateManagementException(ikx.getMessage(), ikx); } catch (OperatorCreationException ocx) { throw new CertificateManagementException(ocx.getMessage(), ocx); } catch (KeyStoreException ksx) { throw new CertificateManagementException(ksx.getMessage(), ksx); } catch (CertificateException cx) { throw new CertificateManagementException(cx.getMessage(), cx); } finally { if (csrFileStreamWriter != null) { IOUtils.closeQuietly(csrFileStreamWriter); } if (csrFileStream != null) { IOUtils.closeQuietly(csrFileStream); } if (csrPemWriter != null) { IOUtils.closeQuietly(csrPemWriter); } if (publicKeyFileStream != null) { IOUtils.closeQuietly(publicKeyFileStream); } if (publicKeyStreamWriter != null) { IOUtils.closeQuietly(publicKeyStreamWriter); } if (publicKeyWriter != null) { IOUtils.closeQuietly(publicKeyWriter); } if (privateKeyFileStream != null) { IOUtils.closeQuietly(privateKeyFileStream); } if (privateKeyStreamWriter != null) { IOUtils.closeQuietly(privateKeyStreamWriter); } if (privateKeyWriter != null) { IOUtils.closeQuietly(privateKeyWriter); } if (keyStoreStream != null) { IOUtils.closeQuietly(keyStoreStream); } } return csrFile; }
From source file:iracing.webapi.IracingWebApi.java
private void installCerts() throws Exception { String host = "members.iracing.com"; int port = 443; char[] password = CERT_STORE_PASSWORD.toCharArray(); File file = new File("jssecacerts"); if (!file.isFile()) { char seperator = File.separatorChar; File dir = new File(System.getProperty("java.home") + seperator + "lib" + seperator + "security"); file = new File(dir, "jssecacerts"); if (!file.isFile()) { file = new File(dir, "cacerts"); }/* w ww .ja v a2 s. com*/ } KeyStore ks; InputStream in = new FileInputStream(file); ks = KeyStore.getInstance(KeyStore.getDefaultType()); try { ks.load(in, password); } catch (Exception e) { } in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); SSLSocket socket = null; try { socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); socket.startHandshake(); } catch (Exception e) { //e.printStackTrace(); } finally { if (socket != null) socket.close(); } X509Certificate[] chain = tm.chain; if (chain == null) return; MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); } for (int count = 0; count < chain.length; count++) { X509Certificate cert = chain[count]; String alias = host + "-" + (count + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); try { ks.store(out, password); } finally { out.close(); } } }