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:strat.mining.stratum.proxy.Launcher.java
/** * Check that a valid SSl certificate already exists. If not, create a new * one./* w w w.j av a2s. com*/ * * @throws Exception */ private static void checkCertificate() throws Exception { File storeFile = new File(ConfigurationManager.getInstance().getDatabaseDirectory(), KEYSTORE_FILE_NAME); KeyStore keyStore = KeyStore.getInstance("JKS"); if (!storeFile.exists()) { LOGGER.info("KeyStore does not exist. Create {}", storeFile.getAbsolutePath()); storeFile.getParentFile().mkdirs(); storeFile.createNewFile(); keyStore.load(null, null); LOGGER.info("Generating new SSL certificate."); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator(); keyGenerator .init(new RSAKeyGenerationParameters(BigInteger.valueOf(101), new SecureRandom(), 2048, 14)); AsymmetricCipherKeyPair keysPair = keyGenerator.generateKeyPair(); RSAKeyParameters rsaPrivateKey = (RSAKeyParameters) keysPair.getPrivate(); RSAPrivateKeySpec rsaPrivSpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getExponent()); RSAKeyParameters rsaPublicKey = (RSAKeyParameters) keysPair.getPublic(); RSAPublicKeySpec rsaPublicSpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getExponent()); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey rsaPriv = kf.generatePrivate(rsaPrivSpec); PublicKey rsaPub = kf.generatePublic(rsaPublicSpec); X500Name issuerDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None"); Integer randomNumber = new SecureRandom().nextInt(); BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); X500Name subjectDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None"); byte[] publickeyb = rsaPub.getEncoded(); ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb); SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore, notAfter, subjectDN, subPubKeyInfo); ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(keysPair.getPrivate()); X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner); Certificate certificate = new CertificateFactory() .engineGenerateCertificate(new ByteBufferBackedInputStream( ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded()))); LOGGER.info("Certificate generated."); keyStore.setKeyEntry(KEYSTORE_KEY_ENTRY_ALIAS, rsaPriv, KEYSTORE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { certificate }); keyStore.store(new FileOutputStream(storeFile), KEYSTORE_PASSWORD.toCharArray()); } }
From source file:com.sun.identity.console.user.model.UMChangeUserPasswordModelImpl.java
public void changePwd(String userId, String oldPassword, String newPassword) throws AMConsoleException { String[] params = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD }; try {/*ww w.java2 s. c o m*/ logEvent("ATTEMPT_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params); AMIdentity amIdentity = IdUtils.getIdentity(getUserSSOToken(), userId); boolean verified = verifyOldPassword(amIdentity, userId, oldPassword.toCharArray()); if (!verified) { String strError = "Authorized for password changed denied"; String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } Map passwordMap = new AMHashMap(2); Set set = new HashSet(2); set.add(newPassword); passwordMap.put(AMAdminConstants.ATTR_USER_PASSWORD, set); Set<String> attributeNames = new HashSet<String>(); attributeNames.add(USERPKCS12_BINARY_ATTRNAME); Map<String, byte[][]> userPKCS12Map = amIdentity.getBinaryAttributes(attributeNames); if (userPKCS12Map != null && userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME) != null) { KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(TOLVEN_CREDENTIAL_FORMAT_PKCS12); } catch (Exception e) { String strError = "Could not get an instance of KeyStore to create user KeyStore: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } byte[][] oldUserPKCS12ByteArrs = (byte[][]) userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME); byte[] oldUserPKCS12 = oldUserPKCS12ByteArrs[0]; ByteArrayInputStream bais = new ByteArrayInputStream(oldUserPKCS12); try { keyStore.load(bais, oldPassword.toCharArray()); } catch (Exception e) { String strError = "Could not get user KeyStore using old password: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } ByteArrayOutputStream baos = null; try { String alias = keyStore.aliases().nextElement(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, oldPassword.toCharArray()); keyStore.setKeyEntry(alias, privateKey, newPassword.toCharArray(), keyStore.getCertificateChain(alias)); baos = new ByteArrayOutputStream(); } catch (Exception e) { String strError = "Could not get Key from user KeyStore: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } try { keyStore.store(baos, newPassword.toCharArray()); } catch (Exception e) { String strError = "Could not save user KeyStore: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } byte[] newUserPKCS12 = baos.toByteArray(); byte[][] newUserPKCS12ByteArrs = new byte[1][]; newUserPKCS12ByteArrs[0] = newUserPKCS12; Map<String, byte[][]> newUserPKCS12Map = newUserPKCS12Map = new HashMap<String, byte[][]>(); newUserPKCS12Map.put(USERPKCS12_BINARY_ATTRNAME, newUserPKCS12ByteArrs); // Ensure that the following two lines are never out of sync (one would expect store() to be a transaction) amIdentity.setBinaryAttributes(newUserPKCS12Map); amIdentity.setAttributes(passwordMap); amIdentity.store(); } else { amIdentity.setAttributes(passwordMap); amIdentity.store(); } logEvent("SUCCEED_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params); } catch (SSOException e) { String strError = getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } catch (IdRepoException e) { String strError = getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("IDM_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } }
From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java
@Override public byte[] generateKeyStore(final AuthenticationToken admin, final EndEntityInformation endEntity) throws AuthorizationDeniedException, EjbcaException { GenerateToken tgen = new GenerateToken(endEntityAuthenticationSessionLocal, endEntityAccessSession, endEntityManagementSessionLocal, caSession, keyRecoverySessionLocal, signSessionLocal); KeyStore keyStore; try {/* w ww .jav a 2 s . c o m*/ keyStore = tgen.generateOrKeyRecoverToken(admin, endEntity.getUsername(), endEntity.getPassword(), endEntity.getCAId(), endEntity.getExtendedinformation().getKeyStoreAlgorithmSubType(), endEntity.getExtendedinformation().getKeyStoreAlgorithmType(), endEntity.getTokenType() == SecConst.TOKEN_SOFT_JKS, false, false, false, endEntity.getEndEntityProfileId()); } catch (Exception e1) { throw new KeyStoreGeneralRaException(e1); } if (endEntity.getTokenType() == EndEntityConstants.TOKEN_SOFT_PEM) { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { outputStream .write(KeyTools.getSinglePemFromKeyStore(keyStore, endEntity.getPassword().toCharArray())); return outputStream.toByteArray(); } catch (IOException | CertificateEncodingException | UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e) { log.error(e); //should never happen if keyStore is valid object } } else { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { keyStore.store(outputStream, endEntity.getPassword().toCharArray()); return outputStream.toByteArray(); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException e) { log.error(e); //should never happen if keyStore is valid object } } return null; }
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
/** * Generates a self-signed certificate based on the keypair and saves it in the keystore. * Should only be used to init the CA./*from w ww . j ava 2 s . c om*/ */ public void initCA(String rootCertX500Name, String mcidregCertX500Name, String crlUrl, String ocspUrl, String outputCaCrlPath) { if (KEYSTORE_PASSWORD == null) { KEYSTORE_PASSWORD = "changeit"; } if (ROOT_KEYSTORE_PATH == null) { ROOT_KEYSTORE_PATH = "mc-root-keystore.jks"; } if (INTERMEDIATE_KEYSTORE_PATH == null) { INTERMEDIATE_KEYSTORE_PATH = "mc-it-keystore.jks"; } if (TRUSTSTORE_PASSWORD == null) { TRUSTSTORE_PASSWORD = "changeit"; } if (TRUSTSTORE_PATH == null) { TRUSTSTORE_PATH = "mc-truststore.jks"; } if (CRL_URL == null) { CRL_URL = crlUrl; } if (OCSP_URL == null) { OCSP_URL = ocspUrl; } KeyPair cakp = generateKeyPair(); KeyPair imkp = generateKeyPair(); KeyStore rootks = null; KeyStore itks; KeyStore ts; FileOutputStream rootfos = null; FileOutputStream itfos = null; FileOutputStream tsfos = null; try { rootks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() rootks.load(null, KEYSTORE_PASSWORD.toCharArray()); itks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() itks.load(null, KEYSTORE_PASSWORD.toCharArray()); // Store away the keystore. rootfos = new FileOutputStream(ROOT_KEYSTORE_PATH); itfos = new FileOutputStream(INTERMEDIATE_KEYSTORE_PATH); X509Certificate cacert; try { cacert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(), cakp.getPublic(), new X500Name(rootCertX500Name), new X500Name(rootCertX500Name), null, "ROOTCA"); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } X509Certificate imcert; try { imcert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(), imkp.getPublic(), new X500Name(rootCertX500Name), new X500Name(mcidregCertX500Name), null, "INTERMEDIATE"); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } Certificate[] certChain = new Certificate[1]; certChain[0] = cacert; rootks.setKeyEntry(ROOT_CERT_ALIAS, cakp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain); rootks.store(rootfos, KEYSTORE_PASSWORD.toCharArray()); rootks = KeyStore.getInstance(KeyStore.getDefaultType()); rootks.load(null, KEYSTORE_PASSWORD.toCharArray()); certChain = new Certificate[2]; certChain[0] = imcert; certChain[1] = cacert; itks.setKeyEntry(INTERMEDIATE_CERT_ALIAS, imkp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain); itks.store(itfos, KEYSTORE_PASSWORD.toCharArray()); // Store away the truststore. ts = KeyStore.getInstance(KeyStore.getDefaultType()); ts.load(null, TRUSTSTORE_PASSWORD.toCharArray()); tsfos = new FileOutputStream(TRUSTSTORE_PATH); ts.setCertificateEntry(ROOT_CERT_ALIAS, cacert); ts.setCertificateEntry(INTERMEDIATE_CERT_ALIAS, imcert); ts.store(tsfos, TRUSTSTORE_PASSWORD.toCharArray()); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { safeClose(rootfos); safeClose(itfos); safeClose(tsfos); KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection( KEYSTORE_PASSWORD.toCharArray()); PrivateKeyEntry rootCertEntry; try { rootCertEntry = (PrivateKeyEntry) rootks.getEntry(ROOT_CERT_ALIAS, protParam); generateRootCACRL(rootCertX500Name, null, rootCertEntry, outputCaCrlPath); } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) { // todo, I think is an irrecoverable state, but we should not throw exception from finally, perhaps this code should not be in a finally block log.error("unable to generate RootCACRL", e); } } }
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 .jav a 2 s. com * 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.signserver.server.cryptotokens.KeystoreCryptoToken.java
@Override public void generateKey(String keyAlgorithm, String keySpec, String alias, char[] authCode, Map<String, Object> params, IServices services) throws CryptoTokenOfflineException, IllegalArgumentException { if (keySpec == null) { throw new IllegalArgumentException("Missing keyspec parameter"); }//w w w .jav a 2 s. com if (alias == null) { throw new IllegalArgumentException("Missing alias parameter"); } if (LOG.isDebugEnabled()) { LOG.debug("keyAlgorithm: " + keyAlgorithm + ", keySpec: " + keySpec + ", alias: " + alias); } try { final KeyStore keystore = getKeyStore(); // Check key generation limit, if configured if (keygenerationLimit != null && keygenerationLimit > -1) { final int current; try { current = keystore.size(); if (current >= keygenerationLimit) { throw new TokenOutOfSpaceException("Key generation limit exceeded: " + current); } } catch (KeyStoreException ex) { LOG.error("Checking key generation limit failed", ex); throw new TokenOutOfSpaceException( "Current number of key entries could not be obtained: " + ex.getMessage(), ex); } } final KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm, "BC"); if ("ECDSA".equals(keyAlgorithm)) { kpg.initialize(ECNamedCurveTable.getParameterSpec(keySpec)); } else { kpg.initialize(Integer.valueOf(keySpec)); } final String sigAlgName = "SHA1With" + keyAlgorithm; LOG.debug("generating..."); final KeyPair keyPair = kpg.generateKeyPair(); Certificate[] chain = new Certificate[1]; chain[0] = CryptoTokenHelper.createDummyCertificate(alias, sigAlgName, keyPair, getProvider(PROVIDERUSAGE_SIGN)); LOG.debug("Creating certificate with entry " + alias + '.'); keystore.setKeyEntry(alias, keyPair.getPrivate(), authCode, chain); final OutputStream os; if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) { os = new ByteArrayOutputStream(); } else { os = new FileOutputStream(new File(keystorepath)); } keystore.store(os, authenticationCode); if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) { final ByteArrayOutputStream baos = (ByteArrayOutputStream) os; final IWorkerSession.ILocal workerSessionLocal = services.get(IWorkerSession.ILocal.class); if (workerSessionLocal == null) { throw new IllegalStateException("No WorkerSession available"); } workerSessionLocal.setKeystoreData(new AdminInfo("Internal", null, null), workerId, baos.toByteArray()); } final KeyEntry entry = new KeyEntry((PrivateKey) keyPair.getPrivate(), chain[0], Arrays.asList(chain)); // If this is the first entry entries.put(alias, entry); if (properties.getProperty(DEFAULTKEY) == null) { properties.setProperty(DEFAULTKEY, alias); entries.put(ICryptoToken.PURPOSE_SIGN, entry); entries.put(ICryptoToken.PURPOSE_DECRYPT, entry); } } catch (UnsupportedOperationException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (KeyStoreException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (NoSuchAlgorithmException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (NoSuchProviderException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (InvalidAlgorithmParameterException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (NumberFormatException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (OperatorCreationException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (CertificateException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (IOException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (IllegalStateException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } }
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"); }//from w ww .j av a 2 s . c o m } 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(); } } }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
public void migrateKeystore() { PropertiesConfiguration properties = new PropertiesConfiguration(); properties.setDelimiterParsingDisabled(true); try {//from w w w . j a v a 2 s.co m if (getProperty(PROPERTIES_CORE, "encryption.key") != null) { // load the keystore path and passwords properties.load(ResourceUtil.getResourceStream(this.getClass(), "mirth.properties")); File keyStoreFile = new File(properties.getString("keystore.path")); char[] keyStorePassword = properties.getString("keystore.storepass").toCharArray(); char[] keyPassword = properties.getString("keystore.keypass").toCharArray(); // delete the old JKS keystore keyStoreFile.delete(); // create and load a new one as type JCEKS KeyStore keyStore = KeyStore.getInstance("JCEKS"); keyStore.load(null, keyStorePassword); // deserialize the XML secret key to an Object ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance(); String xml = getProperty(PROPERTIES_CORE, "encryption.key"); /* * This is a fix to account for an error that occurred when testing migration from * version 1.8.2 to 3.0.0. The key was serialized as an instance of * com.sun.crypto.provider.DESedeKey, but fails to correctly deserialize as an * instance of java.security.KeyRep. The fix below extracts the "<default>" node * from the serialized xml and uses that to deserialize to java.security.KeyRep. * (MIRTH-2552) */ Document document = new DocumentSerializer().fromXML(xml); DonkeyElement root = new DonkeyElement(document.getDocumentElement()); DonkeyElement keyRep = root.getChildElement("java.security.KeyRep"); if (keyRep != null) { DonkeyElement defaultElement = keyRep.getChildElement("default"); if (defaultElement != null) { defaultElement.setNodeName("java.security.KeyRep"); xml = defaultElement.toXml(); } } SecretKey secretKey = serializer.deserialize(xml, SecretKey.class); // add the secret key entry to the new keystore KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKey); keyStore.setEntry(SECRET_KEY_ALIAS, entry, new KeyStore.PasswordProtection(keyPassword)); // save the keystore to the filesystem OutputStream keyStoreOuputStream = new FileOutputStream(keyStoreFile); try { keyStore.store(keyStoreOuputStream, keyStorePassword); } finally { IOUtils.closeQuietly(keyStoreOuputStream); } // remove the property from CONFIGURATION removeProperty(PROPERTIES_CORE, "encryption.key"); // reinitialize the security settings initializeSecuritySettings(); } } catch (Exception e) { logger.error("Error migrating encryption key from database to keystore.", e); } }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Export a key entry containing private key and public key certificate * chain from the Keystore to a PKCS #12 file. */// w ww. j a v a 2s . co m @Override public void exportKeyPair(String alias, Path exportFile, String pkcs12Password) throws CMException { // Need to make sure we are initialized before we do anything else // as Credential Manager can be created but not initialized initialize(); synchronized (keystore) { // Export the key pair try { // Get the private key for the alias PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, masterPassword.toCharArray()); // Get the related public key's certificate chain Certificate[] certChain = getKeyPairsCertificateChain(alias); // Create a new PKCS #12 keystore KeyStore newPkcs12 = KeyStore.getInstance("PKCS12", "BC"); newPkcs12.load(null, null); // Place the private key and certificate chain into the PKCS #12 // keystore. Construct a new alias as // "<SUBJECT_COMMON_NAME>'s <ISSUER_ORGANISATION> ID" String sDN = ((X509Certificate) certChain[0]).getSubjectX500Principal().getName(RFC2253); ParsedDistinguishedName parsedDN = dnParser.parseDN(sDN); String sCN = parsedDN.getCN(); String iDN = ((X509Certificate) certChain[0]).getIssuerX500Principal().getName(RFC2253); parsedDN = dnParser.parseDN(iDN); String iCN = parsedDN.getCN(); String pkcs12Alias = sCN + "'s " + iCN + " ID"; newPkcs12.setKeyEntry(pkcs12Alias, privateKey, new char[0], certChain); // Store the new PKCS #12 keystore on the disk try (OutputStream fos = Files.newOutputStream(exportFile)) { newPkcs12.store(fos, pkcs12Password.toCharArray()); } } catch (Exception ex) { String exMessage = "Failed to export the key pair from the Keystore"; logger.error(exMessage, ex); throw new CMException(exMessage, ex); } } }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Export a key entry containing private key and public key certificate * chain from the Keystore to a PKCS #12 file. */// ww w . j a va 2 s . co m @Override public void exportKeyPair(String alias, File exportFile, String pkcs12Password) throws CMException { /* * Need to make sure we are initialized before we do anything else, as * the Credential Manager can be created but not initialized. */ initialize(); synchronized (keystore) { // Export the key pair try { // Get the private key for the alias PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, masterPassword.toCharArray()); // Get the related public key's certificate chain Certificate[] certChain = getKeyPairsCertificateChain(alias); // Create a new PKCS #12 keystore KeyStore newPkcs12 = KeyStore.getInstance("PKCS12", "BC"); newPkcs12.load(null, null); // Place the private key and certificate chain into the PKCS #12 // keystore. Construct a new alias as // "<SUBJECT_COMMON_NAME>'s <ISSUER_ORGANISATION> ID" String sDN = ((X509Certificate) certChain[0]).getSubjectX500Principal().getName(RFC2253); ParsedDistinguishedName parsedDN = dnParser.parseDN(sDN); String sCN = parsedDN.getCN(); String iDN = ((X509Certificate) certChain[0]).getIssuerX500Principal().getName(RFC2253); parsedDN = dnParser.parseDN(iDN); String iCN = parsedDN.getCN(); String pkcs12Alias = sCN + "'s " + iCN + " ID"; newPkcs12.setKeyEntry(pkcs12Alias, privateKey, new char[0], certChain); // Store the new PKCS #12 keystore on the disk try (FileOutputStream fos = new FileOutputStream(exportFile)) { newPkcs12.store(fos, pkcs12Password.toCharArray()); } } catch (Exception ex) { String exMessage = "Failed to export the key pair from the Keystore"; logger.error(exMessage, ex); throw new CMException(exMessage, ex); } } }