List of usage examples for java.security KeyStore setKeyEntry
public final void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException
From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java
/** * Method that import CA token keys from a P12 file. Was originally used when upgrading from * old EJBCA versions. Only supports SHA1 and SHA256 with RSA or ECDSA and SHA1 with DSA. *//*from www.jav a 2s . c om*/ public void importKeys(String authenticationCode, PrivateKey privatekey, PublicKey publickey, PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain) throws Exception { // If we don't give an authentication code, perhaps we have autoactivation enabled char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode); // Currently only RSA keys are supported KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // The CAs certificate is first in chain Certificate cacert = caSignatureCertChain[0]; // Assume that the same hash algorithm is used for signing that was used to sign this CA cert String signatureAlgorithm = CertTools.getSignatureAlgorithm(cacert); String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey); if (keyAlg == null) { throw new Exception( "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")"); } // If this is a CVC CA we need to find out the sequence if (cacert instanceof CardVerifiableCertificate) { CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert; log.debug("Getting sequence from holderRef in CV certificate."); String sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence(); log.debug("Setting sequence " + sequence); setKeySequence(sequence); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); } else { log.debug("Setting default sequence " + CATokenConstants.DEFAULT_KEYSEQUENCE); setKeySequence(CATokenConstants.DEFAULT_KEYSEQUENCE); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); } // import sign keys. String keyspec = AlgorithmTools.getKeySpecification(publickey); Certificate[] certchain = new Certificate[1]; certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm, true); keystore.setKeyEntry(SoftCAToken.PRIVATESIGNKEYALIAS, privatekey, null, certchain); // generate enc keys. // Encryption keys must be RSA still String encryptionSignatureAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm); keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionSignatureAlgorithm); keyspec = "2048"; KeyPair enckeys = null; if (publicEncryptionKey == null || privateEncryptionKey == null) { enckeys = KeyTools.genKeys(keyspec, keyAlg); } else { enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey); } // generate dummy certificate certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(), enckeys.getPublic(), encryptionSignatureAlgorithm, true); keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain); // Store keystore SoftCATokenInfo info = new SoftCATokenInfo(); info.setEncKeyAlgorithm(keyAlg); info.setEncKeySpec(keyspec); info.setEncryptionAlgorithm(encryptionSignatureAlgorithm); info.setSignKeyAlgorithm(keyAlg); info.setSignKeySpec(keyspec); info.setSignatureAlgorithm(signatureAlgorithm); storeSoftKeyStore(authCode, info, null, keystore); // Finally reset the token so it will be re-read when we want to use it this.catoken = null; }
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. *///from w ww .j a v a 2 s . com @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. *//*from w w w.j a va2 s .c o 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); } } }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
private void saveNodeCertificateChain(KeyStore keyStore, Key key, String keyPassword, X509Certificate nodeCert, X509Certificate[] chain) { if (keyPassword == null) { keyPassword = ""; }/* ww w. ja v a 2s . c om*/ X509Certificate caCert = getCACertificate(keyStore); if (chain.length < 1) { throw new CertificateException("No certificates avaialble"); } if (chain.length > 1) { // we have to trust the parents... the end of the chain must be our CA try { final int caIdx = chain.length - 1; if (caCert == null) { // if we don't have a CA cert yet, install that now log.info("Installing trusted CA certificate {}", chain[caIdx].getSubjectDN()); keyStore.setCertificateEntry(caAlias, chain[caIdx]); caCert = chain[caIdx]; } else { // verify CA is the same... maybe we shouldn't do this? if (!chain[caIdx].getSubjectDN().equals(caCert.getSubjectDN())) { throw new CertificateException("Chain CA " + chain[caIdx].getSubjectDN().getName() + " does not match expected " + caCert.getSubjectDN().getName()); } if (!chain[caIdx].getIssuerDN().equals(caCert.getIssuerDN())) { throw new CertificateException("Chain CA " + chain[caIdx].getIssuerDN().getName() + " does not match expected " + caCert.getIssuerDN().getName()); } } // install intermediate certs... for (int i = caIdx - 1, j = 1; i > 0; i--, j++) { String alias = caAlias + "sub" + j; log.info("Installing trusted intermediate certificate {}", chain[i].getSubjectDN()); keyStore.setCertificateEntry(alias, chain[i]); } } catch (KeyStoreException e) { throw new CertificateException("Error storing CA chain", e); } } else { // put CA at end of chain if (caCert == null) { throw new CertificateException("No CA certificate available"); } chain = new X509Certificate[] { chain[0], caCert }; } // the issuer must be our CA cert subject... if (!chain[0].getIssuerDN().equals(chain[1].getSubjectDN())) { throw new CertificateException("Issuer " + chain[0].getIssuerDN().getName() + " does not match expected " + chain[1].getSubjectDN().getName()); } // the subject must be our node's existing subject... if (!chain[0].getSubjectDN().equals(nodeCert.getSubjectDN())) { throw new CertificateException("Subject " + chain[0].getIssuerDN().getName() + " does not match expected " + nodeCert.getSubjectDN().getName()); } log.info("Installing node certificate {} reply {} issued by {}", chain[0].getSerialNumber(), chain[0].getSubjectDN().getName(), chain[0].getIssuerDN().getName()); try { keyStore.setKeyEntry(nodeAlias, key, keyPassword.toCharArray(), chain); } catch (KeyStoreException e) { throw new CertificateException("Error opening node certificate", e); } }
From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java
private void getPFXTransacted(Collection<X509Certificate> certificates, char[] password, boolean includeRoot, OutputStream pfx) throws KeyStoreException { try {//w ww . j a va 2s . c o m KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); keyStore.load(null); for (X509Certificate certificate : certificates) { if (certificate == null) { continue; } X509CertStoreEntry entry = keyAndCertStore.getByCertificate(certificate); if (entry != null && entry.getCertificate() != null) { KeyAndCertificate keyAndCertificate = keyAndCertStore.getKeyAndCertificate(entry); if (keyAndCertificate != null) { if (!certificate.equals(keyAndCertificate.getCertificate())) { throw new IllegalStateException("Certificate mismatch."); } X509Certificate[] chain = null; /* * Build a certificate chain so we add the chain (if valid) */ try { CertificatePathBuilder pathBuilder = pathBuilderFactory.createCertificatePathBuilder(); CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate); X509Certificate root = null; if (includeRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) { TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult) .getTrustAnchor(); if (trustAnchor != null) { root = trustAnchor.getTrustedCert(); } } CertPath certPath = pathBuilderResult.getCertPath(); if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) { List<X509Certificate> completePath = new LinkedList<X509Certificate>(); for (Certificate fromPath : certPath.getCertificates()) { if (!(fromPath instanceof X509Certificate)) { /* * only X509Certificates are supported */ continue; } completePath.add((X509Certificate) fromPath); } if (root != null && includeRoot) { completePath.add(root); } chain = new X509Certificate[completePath.size()]; chain = completePath.toArray(chain); } } catch (CertPathBuilderException e) { logger.warn( "Could not build a path. Message: " + ExceptionUtils.getRootCauseMessage(e)); } if (ArrayUtils.getLength(chain) == 0) { chain = new X509Certificate[] { certificate }; } String alias = X509CertificateInspector.getThumbprint(certificate); if (keyAndCertificate.getPrivateKey() != null) { keyStore.setKeyEntry(alias, keyAndCertificate.getPrivateKey(), password, chain); } else { keyStore.setCertificateEntry(alias, certificate); } } } } keyStore.store(pfx, password); } catch (NoSuchAlgorithmException e) { throw new KeyStoreException(e); } catch (CertificateException e) { throw new KeyStoreException(e); } catch (IOException e) { throw new KeyStoreException(e); } catch (CertStoreException e) { throw new KeyStoreException(e); } catch (NoSuchProviderException e) { throw new NoSuchProviderRuntimeException(e); } catch (SecurityFactoryFactoryException e) { throw new KeyStoreException(e); } }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Change the Keystore and the Truststore's master password to the one * provided. The Keystore and Truststore both use the same password. *///from w w w. j av a2 s. com @Override public void changeMasterPassword(String newMasterPassword) throws CMException { // Need to make sure we are initialized before we do anything else // as Credential Manager can be created but not initialized initialize(); String oldMasterPassword = masterPassword; KeyStore oldKeystore = keystore; KeyStore oldTruststore = truststore; try { synchronized (keystore) { // Create a new keystore and copy all items from the current // one, encrypting them with the new password KeyStore newKeystore = null; try { // Try to create Taverna's Keystore as Bouncy Castle // UBER-type keystore. newKeystore = KeyStore.getInstance("UBER", "BC"); } catch (Exception ex) { // The requested keystore type is not available from // security providers. String exMessage = "Failed to instantiate a new Bouncy Castle Keystore when changing master password."; throw new CMException(exMessage, ex); } try { // Initialize a new empty keystore newKeystore.load(null, null); } catch (Exception ex) { String exMessage = "Failed to create a new empty Keystore to copy over the entries from the current one."; throw new CMException(exMessage, ex); } Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (REALLY_DISABLED) { if (alias.startsWith("password#")) { // a password entry SecretKeySpec passwordKey = (((SecretKeySpec) keystore.getKey(alias, masterPassword.toCharArray()))); newKeystore.setKeyEntry(alias, passwordKey, newMasterPassword.toCharArray(), null); } else if (alias.startsWith("keypair#")) { // a private key entry // 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 = keystore.getCertificateChain(alias); newKeystore.setKeyEntry(alias, privateKey, newMasterPassword.toCharArray(), certChain); } } // Do all entries at once, not reason to separate password & // key pair entries newKeystore.setEntry(alias, keystore.getEntry(alias, new KeyStore.PasswordProtection(masterPassword.toCharArray())), new KeyStore.PasswordProtection(newMasterPassword.toCharArray())); } try (FileOutputStream fos = new FileOutputStream(keystoreFile)) { newKeystore.store(fos, newMasterPassword.toCharArray()); } keystore = newKeystore; } // Truststore does not need to be re-encrypeted item by item as // entries there are not encrypted, just the whole truststore synchronized (truststore) { try (FileOutputStream fos = new FileOutputStream(truststoreFile)) { truststore.store(fos, newMasterPassword.toCharArray()); } } // Set the new master password as well masterPassword = newMasterPassword; } catch (Exception ex) { // rollback keystore = oldKeystore; truststore = oldTruststore; masterPassword = oldMasterPassword; saveKeystore(KEYSTORE); saveKeystore(TRUSTSTORE); String exMessage = "Failed to change maaster password - reverting to the old one"; logger.error(exMessage, ex); throw (new CMException(exMessage)); } }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Change the Keystore and the Truststore's master password to the one * provided. The Keystore and Truststore both use the same password. */// ww w .jav a 2s. co m @Override public void changeMasterPassword(String newMasterPassword) 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(); String oldMasterPassword = masterPassword; KeyStore oldKeystore = keystore; KeyStore oldTruststore = truststore; try { synchronized (keystore) { // Create a new keystore and copy all items from the current // one, encrypting them with the new password KeyStore newKeystore = null; try { // Try to create Taverna's Keystore as Bouncy Castle // UBER-type keystore. newKeystore = KeyStore.getInstance("UBER", "BC"); } catch (Exception ex) { // The requested keystore type is not available from // security providers. String exMessage = "Failed to instantiate a new Bouncy Castle Keystore when changing master password."; throw new CMException(exMessage, ex); } try { // Initialize a new empty keystore newKeystore.load(null, null); } catch (Exception ex) { String exMessage = "Failed to create a new empty Keystore to copy over the entries from the current one."; throw new CMException(exMessage, ex); } Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (REALLY_DISABLED) { if (alias.startsWith("password#")) { // a password entry SecretKeySpec passwordKey = (((SecretKeySpec) keystore.getKey(alias, masterPassword.toCharArray()))); newKeystore.setKeyEntry(alias, passwordKey, newMasterPassword.toCharArray(), null); } else if (alias.startsWith("keypair#")) { // a private key entry // 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 = keystore.getCertificateChain(alias); newKeystore.setKeyEntry(alias, privateKey, newMasterPassword.toCharArray(), certChain); } } /* * Do all entries at once, not reason to separate password & * key pair entries */ newKeystore.setEntry(alias, keystore.getEntry(alias, new KeyStore.PasswordProtection(masterPassword.toCharArray())), new KeyStore.PasswordProtection(newMasterPassword.toCharArray())); } try (FileOutputStream fos = new FileOutputStream(keystoreFile)) { newKeystore.store(fos, newMasterPassword.toCharArray()); } keystore = newKeystore; } /* * Truststore does not need to be re-encrypeted item by item as * entries there are not encrypted, just the whole truststore */ synchronized (truststore) { try (FileOutputStream fos = new FileOutputStream(truststoreFile)) { truststore.store(fos, newMasterPassword.toCharArray()); } } // Set the new master password as well masterPassword = newMasterPassword; } catch (Exception ex) { // rollback keystore = oldKeystore; truststore = oldTruststore; masterPassword = oldMasterPassword; saveKeystore(KEYSTORE); saveKeystore(TRUSTSTORE); String exMessage = "Failed to change maaster password - reverting to the old one"; logger.error(exMessage, ex); throw new CMException(exMessage); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
/** * Method that import CA token keys from a P12 file. Was originally used when upgrading from old EJBCA versions. Only supports SHA1 and SHA256 * with RSA or ECDSA and SHA1 with DSA.//from www .jav a 2s . co m * @throws OperatorCreationException * @throws AuthorizationDeniedException */ private CAToken importKeysToCAToken(AuthenticationToken authenticationToken, String authenticationCode, Properties caTokenProperties, PrivateKey privatekey, PublicKey publickey, PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain, int caId) throws CryptoTokenAuthenticationFailedException, IllegalCryptoTokenException, OperatorCreationException, AuthorizationDeniedException { // If we don't give an authentication code, perhaps we have autoactivation enabled if (StringUtils.isEmpty(authenticationCode)) { String msg = intres.getLocalizedMessage("token.authcodemissing", Integer.valueOf(caId)); log.info(msg); throw new CryptoTokenAuthenticationFailedException(msg); } if (caTokenProperties == null) { caTokenProperties = new Properties(); } try { // Currently only RSA keys are supported KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // The CAs certificate is first in chain Certificate cacert = caSignatureCertChain[0]; // Assume that the same hash algorithm is used for signing that was used to sign this CA cert String signatureAlgorithm = AlgorithmTools.getSignatureAlgorithm(cacert); String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey); if (keyAlg == null) { throw new IllegalCryptoTokenException( "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")"); } // import sign keys. final Certificate[] certchain = new Certificate[1]; certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm, true); keystore.setKeyEntry(CAToken.SOFTPRIVATESIGNKEYALIAS, privatekey, null, certchain); // generate enc keys. // Encryption keys must be RSA still final String encryptionAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm); keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionAlgorithm); final String enckeyspec = "2048"; KeyPair enckeys = null; if (publicEncryptionKey == null || privateEncryptionKey == null) { enckeys = KeyTools.genKeys(enckeyspec, keyAlg); } else { enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey); } // generate dummy certificate certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(), enckeys.getPublic(), encryptionAlgorithm, true); keystore.setKeyEntry(CAToken.SOFTPRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain); // Set the token properties caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, CAToken.SOFTPRIVATEDECKEYALIAS); // Write the keystore to byte[] that we can feed to crypto token factory final char[] authCode = authenticationCode.toCharArray(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, authCode); // Now we have the PKCS12 keystore, from this we can create the CAToken final Properties cryptoTokenProperties = new Properties(); int cryptoTokenId; try { cryptoTokenId = createCryptoTokenWithUniqueName(authenticationToken, "ImportedCryptoToken" + caId, SoftCryptoToken.class.getName(), cryptoTokenProperties, baos.toByteArray(), authCode); } catch (NoSuchSlotException e1) { throw new RuntimeException( "Attempte to define a slot for a soft crypto token. This should not happen."); } final CAToken catoken = new CAToken(cryptoTokenId, caTokenProperties); // If this is a CVC CA we need to find out the sequence String sequence = CAToken.DEFAULT_KEYSEQUENCE; if (cacert instanceof CardVerifiableCertificate) { CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert; log.debug("Getting sequence from holderRef in CV certificate."); try { sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence(); } catch (NoSuchFieldException e) { log.error("Can not get sequence from holderRef in CV certificate, using default sequence."); } } log.debug("Setting sequence " + sequence); catoken.setKeySequence(sequence); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); catoken.setSignatureAlgorithm(signatureAlgorithm); catoken.setEncryptionAlgorithm(encryptionAlgorithm); return catoken; } catch (KeyStoreException e) { throw new IllegalCryptoTokenException(e); } catch (NoSuchProviderException e) { throw new IllegalCryptoTokenException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalCryptoTokenException(e); } catch (CertificateException e) { throw new IllegalCryptoTokenException(e); } catch (IOException e) { throw new IllegalCryptoTokenException(e); } catch (IllegalStateException e) { throw new IllegalCryptoTokenException(e); } catch (InvalidAlgorithmParameterException e) { throw new IllegalCryptoTokenException(e); } catch (CryptoTokenOfflineException e) { throw new IllegalCryptoTokenException(e); } }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
/** * Checks for an existing certificate to use for secure communication between the server and * client. If no certficate exists, this will generate a new one. * // w w w.jav a 2s . com */ private void generateDefaultCertificate(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { final String certificateAlias = "mirthconnect"; if (!keyStore.containsAlias(certificateAlias)) { // Common CA and SSL cert attributes Date startDate = new Date(); // time from which certificate is valid Date expiryDate = DateUtils.addYears(startDate, 50); // time after which certificate is not valid KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider); keyPairGenerator.initialize(2048); KeyPair caKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for CA cert using provider: " + provider.getName()); // Generate CA cert X500Name caSubjectName = new X500Name("CN=Mirth Connect Certificate Authority"); SubjectPublicKeyInfo caSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(caKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caSubjectName, BigInteger.ONE, startDate, expiryDate, caSubjectName, caSubjectKey); certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.basicConstraints, true, new BasicConstraints(0)); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate caCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(certBuilder.build(sigGen)); // Generate SSL cert KeyPair sslKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for SSL cert using provider: " + provider.getName()); X500Name sslSubjectName = new X500Name("CN=mirth-connect"); SubjectPublicKeyInfo sslSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(sslKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder sslCertBuilder = new X509v3CertificateBuilder(caSubjectName, new BigInteger(50, new SecureRandom()), startDate, expiryDate, sslSubjectName, sslSubjectKey); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded())); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(sslKeyPair.getPublic().getEncoded())); sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate sslCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(sslCertBuilder.build(sigGen)); logger.debug("generated new certificate with serial number: " + ((X509Certificate) sslCert).getSerialNumber()); // add the generated SSL cert to the keystore using the key password keyStore.setKeyEntry(certificateAlias, sslKeyPair.getPrivate(), keyPassword, new Certificate[] { sslCert }); } else { logger.debug("found certificate in keystore"); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public byte[] exportCAKeyStore(AuthenticationToken admin, String caname, String keystorepass, String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) { log.trace(">exportCAKeyStore"); try {//from w w w .j a va 2 s . c om final CA thisCa = caSession.getCAForEdit(admin, caname); // Make sure we are not trying to export a hard or invalid token CAToken thisCAToken = thisCa.getCAToken(); final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId()); if (!(cryptoToken instanceof SoftCryptoToken)) { throw new IllegalCryptoTokenException("Cannot export anything but a soft token."); } // Do not allow export without password protection if (StringUtils.isEmpty(keystorepass) || StringUtils.isEmpty(privkeypass)) { throw new IllegalArgumentException("Cannot export a token without password protection."); } // Check authorization if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) { String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoexportcatoken", caname); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details); throw new AuthorizationDeniedException(msg); } // Fetch keys final char[] password = keystorepass.toCharArray(); ((SoftCryptoToken) cryptoToken).checkPasswordBeforeExport(password); cryptoToken.activate(password); PrivateKey p12PrivateEncryptionKey = cryptoToken .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT)); PublicKey p12PublicEncryptionKey = cryptoToken .getPublicKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT)); PrivateKey p12PrivateCertSignKey = cryptoToken .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); PrivateKey p12PrivateCRLSignKey = cryptoToken .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)); if (!p12PrivateCertSignKey.equals(p12PrivateCRLSignKey)) { throw new Exception("Assertion of equal signature keys failed."); } // Proceed with the export byte[] ret = null; String format = null; if (thisCa.getCAType() == CAInfo.CATYPE_CVC) { log.debug("Exporting private key with algorithm: " + p12PrivateCertSignKey.getAlgorithm() + " of format: " + p12PrivateCertSignKey.getFormat()); format = p12PrivateCertSignKey.getFormat(); ret = p12PrivateCertSignKey.getEncoded(); } else { log.debug("Exporting PKCS12 keystore"); format = "PKCS12"; KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, keystorepass.toCharArray()); // Load keys into keystore Certificate[] certificateChainSignature = (Certificate[]) thisCa.getCertificateChain() .toArray(new Certificate[0]); Certificate[] certificateChainEncryption = new Certificate[1]; // certificateChainSignature[0].getSigAlgName(), // generate dummy certificate for encryption key. certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null, p12PrivateEncryptionKey, p12PublicEncryptionKey, thisCAToken.getEncryptionAlgorithm(), true, X509KeyUsage.keyEncipherment, true); log.debug("Exporting with sigAlgorithm " + AlgorithmTools.getSignatureAlgorithm(certificateChainSignature[0]) + "encAlgorithm=" + thisCAToken.getEncryptionAlgorithm()); if (keystore.isKeyEntry(privateSignatureKeyAlias)) { throw new Exception("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore."); } if (keystore.isKeyEntry(privateEncryptionKeyAlias)) { throw new Exception("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore."); } keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass.toCharArray(), certificateChainSignature); keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass.toCharArray(), certificateChainEncryption); // Return KeyStore as byte array and clean up ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, keystorepass.toCharArray()); if (keystore.isKeyEntry(privateSignatureKeyAlias)) { keystore.deleteEntry(privateSignatureKeyAlias); } if (keystore.isKeyEntry(privateEncryptionKeyAlias)) { keystore.deleteEntry(privateEncryptionKeyAlias); } ret = baos.toByteArray(); } String msg = intres.getLocalizedMessage("caadmin.exportedca", caname, format); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details); log.trace("<exportCAKeyStore"); return ret; } catch (Exception e) { String msg = intres.getLocalizedMessage("caadmin.errorexportca", caname, "PKCS12", e.getMessage()); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), null, null, null, details); throw new EJBException(e); } }