List of usage examples for java.security KeyStore store
public final void store(OutputStream stream, char[] password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * Method to update the certificate which matches the given alias. * * @param certificate: The base64 encoded certificate string. * @param alias : Alias of the certificate that should be retrieved. * @return :/*w w w . j av a 2 s . c o m*/ */ public ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException { InputStream certificateStream = null; try { File trustStoreFile = new File(TRUST_STORE); localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (trustStore.getCertificate(alias) == null) { log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found" + " in the trust store."); return ResponseCode.CERTIFICATE_NOT_FOUND; } //Generate the certificate from the input string. byte[] cert = (Base64.decodeBase64(certificate.getBytes(CHARSET_UTF_8))); certificateStream = new ByteArrayInputStream(cert); if (certificateStream.available() == 0) { log.error("Certificate is empty for the provided alias " + alias); return ResponseCode.INTERNAL_SERVER_ERROR; } CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE); Certificate newCertificate = certificateFactory.generateCertificate(certificateStream); X509Certificate x509Certificate = (X509Certificate) newCertificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { log.error("Could not update the certificate. The certificate expired."); return ResponseCode.CERTIFICATE_EXPIRED; } // If the certificate is not expired, delete the existing certificate and add the new cert. trustStore.deleteEntry(alias); //Store the certificate in the trust store. trustStore.setCertificateEntry(alias, newCertificate); fileOutputStream = new FileOutputStream(trustStoreFile); trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD); } catch (IOException e) { throw new CertificateManagementException("Error updating certificate.", e); } catch (CertificateException e) { throw new CertificateManagementException("Error generating the certificate.", e); } catch (NoSuchAlgorithmException e) { throw new CertificateManagementException("Error loading the keystore.", e); } catch (KeyStoreException e) { throw new CertificateManagementException("Error updating the certificate in the keystore.", e); } finally { closeStreams(fileOutputStream, certificateStream, localTrustStoreStream); } return ResponseCode.SUCCESS; }
From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java
/** * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String) */// w w w . j a v a 2s . c o m public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException { final String methodName = ICertificateManager.CNAME + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", commonName); DEBUGGER.debug("Value: {}", certificateFile); DEBUGGER.debug("Value: {}", keystoreFile); } final File rootDirectory = certConfig.getRootDirectory(); final File certificateDirectory = FileUtils .getFile(certConfig.getCertificateDirectory() + "/" + commonName); final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName); if (DEBUG) { DEBUGGER.debug("rootDirectory: {}", rootDirectory); DEBUGGER.debug("certificateDirectory: {}", certificateDirectory); DEBUGGER.debug("storeDirectory: {}", storeDirectory); DEBUGGER.debug("certificateFile: {}", certificateFile); DEBUGGER.debug("keystoreFile: {}", keystoreFile); } boolean isComplete = false; FileInputStream certStream = null; FileOutputStream storeStream = null; FileInputStream keystoreInput = null; FileInputStream rootCertStream = null; FileInputStream intermediateCertStream = null; try { if (!(rootDirectory.exists())) { throw new CertificateManagementException( "Root certificate directory either does not exist or cannot be written to. Cannot continue."); } if (!(rootDirectory.canWrite())) { throw new CertificateManagementException( "Root certificate directory either does not exist or cannot be written to. Cannot continue."); } if (!(certConfig.getRootCertificateFile().exists())) { throw new CertificateManagementException("Root certificate file does not exist. Cannot continue."); } if (!(certConfig.getIntermediateCertificateFile().exists())) { throw new CertificateManagementException( "Intermediate certificate file does not exist. Cannot continue."); } if (!(storeDirectory.canWrite())) { throw new CertificateManagementException( "Keystore directory either does not exist or cannot be written to. Cannot continue."); } if (!(keystoreFile.canWrite())) { throw new CertificateManagementException( "Unable to write to applicable keystore. Cannot continue."); } keystoreInput = FileUtils.openInputStream(keystoreFile); certStream = FileUtils.openInputStream(certificateFile); if (DEBUG) { DEBUGGER.debug("keystoreInput: {}", keystoreInput); DEBUGGER.debug("certStream: {}", certStream); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(keystoreInput, storePassword.toCharArray()); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray()); CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType()); if (DEBUG) { DEBUGGER.debug("CertificateFactory: {}", certFactory); } rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile())); intermediateCertStream = FileUtils .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile())); if (DEBUG) { DEBUGGER.debug("rootCertStream: {}", rootCertStream); DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream); } X509Certificate[] responseCert = new X509Certificate[] { (X509Certificate) certFactory.generateCertificate(rootCertStream), (X509Certificate) certFactory.generateCertificate(intermediateCertStream), (X509Certificate) certFactory.generateCertificate(certStream) }; if (DEBUG) { DEBUGGER.debug("X509Certificate[]", (Object) responseCert); } storeStream = FileUtils.openOutputStream(keystoreFile); keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert); keyStore.store(storeStream, storePassword.toCharArray()); isComplete = true; } 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 (KeyStoreException ksx) { throw new CertificateManagementException(ksx.getMessage(), ksx); } catch (CertificateException cx) { throw new CertificateManagementException(cx.getMessage(), cx); } catch (UnrecoverableKeyException ukx) { throw new CertificateManagementException(ukx.getMessage(), ukx); } finally { if (storeStream != null) { IOUtils.closeQuietly(storeStream); } if (intermediateCertStream != null) { IOUtils.closeQuietly(intermediateCertStream); } if (rootCertStream != null) { IOUtils.closeQuietly(rootCertStream); } if (certStream != null) { IOUtils.closeQuietly(certStream); } if (keystoreInput != null) { IOUtils.closeQuietly(keystoreInput); } } return isComplete; }
From source file:org.guanxi.idp.Bootstrap.java
public boolean createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null; try {//from w w w . j av a 2 s . c om ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
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. * This REST call allows a Cloud.com account holder to remove a previouly "loaded" X509 * certificate out of the EC2 service.//from w w w. j a v a 2 s . c o m * * This is an unauthenticated 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. */ private void deleteCertificate(HttpServletRequest request, HttpServletResponse response) throws Exception { Transaction txn = null; try { String[] accessKey = request.getParameterValues("AWSAccessKeyId"); if (null == accessKey || 0 == accessKey.length) { response.sendError(530, "Missing AWSAccessKeyId parameter"); return; } // -> delete the specified entry and save back to disk FileInputStream fsIn = new FileInputStream(pathToKeystore); KeyStore certStore = KeyStore.getInstance("JKS"); certStore.load(fsIn, keystorePassword.toCharArray()); if (certStore.containsAlias(accessKey[0])) { certStore.deleteEntry(accessKey[0]); FileOutputStream fsOut = new FileOutputStream(pathToKeystore); certStore.store(fsOut, keystorePassword.toCharArray()); // -> dis-associate the cert's uniqueId with the Cloud API keys /* UserCredentialsDao credentialDao = new UserCredentialsDao(); credentialDao.setCertificateId( accessKey[0], null ); */ txn = Transaction.open(Transaction.AWSAPI_DB); UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]); user.setCertUniqueId(null); ucDao.update(user.getId(), user); response.setStatus(200); endResponse(response, "User certificate deleted successfully"); txn.commit(); } else response.setStatus(404); } catch (NoSuchObjectException e) { logger.error("SetCertificate exception " + e.getMessage(), e); response.sendError(404, "SetCertificate exception " + e.getMessage()); } catch (Exception e) { logger.error("DeleteCertificate exception " + e.getMessage(), e); response.sendError(500, "DeleteCertificate exception " + e.getMessage()); } finally { txn.close(); } }
From source file:it.cnr.icar.eric.common.security.KeystoreMover.java
public void move(String sourceKeystoreType, String sourceKeystorePath, String sourceKeystorePassword, String sourceAlias, String sourceKeyPassword, String destinationKeystoreType, String destinationKeystorePath, String destinationKeystorePassword, String destinationAlias, String destinationKeyPassword) throws Exception { char[] sourceKeystorePasswordArr = null; if (sourceKeystorePassword != null) { sourceKeystorePasswordArr = sourceKeystorePassword.toCharArray(); }/*from w w w . j a v a2 s. c o m*/ char[] sourceKeyPasswordArr = sourceKeystorePasswordArr; if (sourceKeyPassword != null) { sourceKeyPasswordArr = sourceKeyPassword.toCharArray(); } char[] destinationKeystorePasswordArr = null; if (destinationKeystorePassword != null) { destinationKeystorePasswordArr = destinationKeystorePassword.toCharArray(); } char[] destinationKeyPasswordArr = destinationKeystorePasswordArr; if (destinationKeyPassword != null) { destinationKeyPasswordArr = destinationKeyPassword.toCharArray(); } FileInputStream in; // -------- Load source keystore to memory --------- in = new FileInputStream(sourceKeystorePath); KeyStore ksin = KeyStore.getInstance(sourceKeystoreType); ksin.load(in, sourceKeystorePasswordArr); in.close(); // -------- Load destination keystore initial contents to memory --------- KeyStore ksout = KeyStore.getInstance(destinationKeystoreType); try { in = new FileInputStream(destinationKeystorePath); ksout.load(in, destinationKeystorePasswordArr); } catch (java.io.FileNotFoundException e) { ksout.load(null, destinationKeystorePasswordArr); } finally { in.close(); } Enumeration<String> en = ksin.aliases(); while (en.hasMoreElements()) { String alias = en.nextElement(); if ((sourceAlias == null) || (sourceAlias.equalsIgnoreCase(alias))) { if (ksout.containsAlias(alias)) { log.info(CommonResourceBundle.getInstance().getString( "message.destinationKeystorePathAlreadyContains", new Object[] { destinationKeystorePath, alias })); continue; } //Use existing alias if no destinationAlias specified if (destinationAlias == null) { destinationAlias = alias; } if (ksin.isCertificateEntry(alias)) { log.debug(CommonResourceBundle.getInstance().getString("message.importingCertificate", new Object[] { alias })); ksout.setCertificateEntry(destinationAlias, ksin.getCertificate(alias)); } if (ksin.isKeyEntry(alias)) { log.debug(CommonResourceBundle.getInstance().getString("message.importingKey", new Object[] { alias })); Certificate[] certChain = ksin.getCertificateChain(alias); ksout.setKeyEntry(destinationAlias, ksin.getKey(alias, sourceKeyPasswordArr), destinationKeyPasswordArr, certChain); } } } //--------- Overwrite the destination keystore with new keys/certs which is a merge of source and original destination keystores-------------- FileOutputStream out = new FileOutputStream(destinationKeystorePath); ksout.store(out, destinationKeystorePasswordArr); out.close(); log.debug(CommonResourceBundle.getInstance().getString("message.keystoreCopySuccessful")); }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
@Override public void initializeSecuritySettings() { try {//from www . j a va 2 s. c om /* * Load the encryption settings so that they can be referenced client side. */ encryptionConfig = new EncryptionSettings(ConfigurationConverter.getProperties(mirthConfig)); File keyStoreFile = new File(mirthConfig.getString("keystore.path")); char[] keyStorePassword = mirthConfig.getString("keystore.storepass").toCharArray(); char[] keyPassword = mirthConfig.getString("keystore.keypass").toCharArray(); Provider provider = (Provider) Class.forName(encryptionConfig.getSecurityProvider()).newInstance(); KeyStore keyStore = null; // if the current server version is pre-2.2, load the keystore as JKS if (MigrationUtil.compareVersions("2.2.0", getServerVersion()) == 1) { keyStore = KeyStore.getInstance("JKS"); } else { keyStore = KeyStore.getInstance("JCEKS"); } if (keyStoreFile.exists()) { keyStore.load(new FileInputStream(keyStoreFile), keyStorePassword); logger.debug("found and loaded keystore: " + keyStoreFile.getAbsolutePath()); } else { keyStore.load(null, keyStorePassword); logger.debug("keystore file not found, created new one"); } configureEncryption(provider, keyStore, keyPassword); generateDefaultCertificate(provider, keyStore, keyPassword); // write the kesytore back to the file FileOutputStream fos = new FileOutputStream(keyStoreFile); keyStore.store(fos, keyStorePassword); IOUtils.closeQuietly(fos); } catch (Exception e) { logger.error("Could not initialize security settings.", e); } }
From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java
protected void createKeyStore(KeyStoreParameters keyStoreParameters, KeyMap keys) { KeyInfoManager keyInfoManager = null; try {//from w ww . j av a 2s . co m if (!keyStoreExists(keyStoreParameters.getLocation())) { keyInfoManager = getKeyInfoManager(keyStoreParameters.getKeyMetaDataFileLocation()); KeyStore ks = initialiseKeyStore(keyStoreParameters.getType(), keyStoreParameters.getProvider()); String keyStorePassword = keyInfoManager.getKeyStorePassword(); if (keyStorePassword == null) { throw new AlfrescoRuntimeException("Key store password is null for keystore at location " + getKeyStoreParameters().getLocation() + ", key store meta data location" + getKeyMetaDataFileLocation()); } for (String keyAlias : keys.getKeyAliases()) { KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias); Key key = keys.getKey(keyAlias); if (key == null) { logger.warn("Key with alias " + keyAlias + " is null when creating keystore at location " + keyStoreParameters.getLocation()); } else { ks.setKeyEntry(keyAlias, key, keyInfo.getPassword().toCharArray(), null); } } // try // { // throw new Exception("Keystore creation: " + ); // } // catch(Throwable e) // { // logger.debug(e.getMessage()); // e.printStackTrace(); // } ks.store(new FileOutputStream(keyStoreParameters.getLocation()), keyStorePassword.toCharArray()); } else { logger.warn("Can't create key store " + keyStoreParameters.getLocation() + ", already exists."); } } catch (Throwable e) { throw new AlfrescoRuntimeException("Failed to create keystore: \n" + " Location: " + keyStoreParameters.getLocation() + "\n" + " Provider: " + keyStoreParameters.getProvider() + "\n" + " Type: " + keyStoreParameters.getType(), e); } finally { if (keyInfoManager != null) { keyInfoManager.clear(); } } }
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 {//from w ww . j ava 2 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 {/*from w ww . ja v a 2 s. co 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("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(); } } } }