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.wso2.carbon.keystore.mgt.KeyStoreGenerator.java
/** * This method generates the keypair and stores it in the keystore * * @param keyStore A keystore instance//from w ww. j a v a2 s. c om * @return Generated public key for the tenant * @throws KeyStoreMgtException Error when generating key pair */ private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException { try { CryptoUtil.getDefaultCryptoUtil(); //generate key pair KeyPairGenerator keyPairGenerator = null; keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Common Name and alias for the generated certificate String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None"; //generate certificates AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("MD5WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory .createKey(keyPair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(new X500Name(commonName), BigInteger.valueOf(new SecureRandom().nextInt()), notBefore, notAfter, new X500Name(commonName), subPubKeyInfo); X509CertificateHolder certificateHolder = v3CertBuilder.build(sigGen); X509Certificate PKCertificate = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certificateHolder); //add private key to KS keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { PKCertificate }); return PKCertificate; } catch (Exception ex) { String msg = "Error while generating the certificate for tenant :" + tenantDomain + "."; log.error(msg, ex); throw new KeyStoreMgtException(msg, ex); } }
From source file:org.tolven.config.model.CredentialManager.java
public void changeGroupCredentialPassword(PasswordInfo passwordInfo, char[] oldPassword, char[] newPassword) throws IOException, GeneralSecurityException { if (oldPassword == null) throw new RuntimeException("Old password '" + passwordInfo.getRefId() + "' is null"); if (!getPasswordHolder().verify(passwordInfo, oldPassword)) throw new RuntimeException("Old Password is invalid for '" + passwordInfo.getRefId() + "'"); if (newPassword == null) throw new RuntimeException("New password '" + passwordInfo.getRefId() + "' is null"); CertificateGroupDetail certGroup = getTolvenConfigWrapper().getCredentialGroup(passwordInfo.getRefId()); CertificateKeyDetail keyDetail = certGroup.getKey(); PrivateKey privateKey = getPrivateKey(keyDetail, oldPassword); File keyFile = new File(keyDetail.getSource()); KeyStore keyStore = null; File keyStoreFile = null;/*from ww w . j a va 2 s . c o m*/ CertificateKeyStoreDetail certKeyStoreDetail = certGroup.getKeyStore(); if (certKeyStoreDetail != null) { keyStore = getTolvenConfigWrapper().getKeyStore(oldPassword, certKeyStoreDetail); keyStoreFile = new File(certKeyStoreDetail.getSource()); } TrustStoreDetail trustStoreDetail = getTolvenConfigWrapper().getTrustStoreDetail(passwordInfo.getRefId()); KeyStore trustStore = null; File trustStoreFile = null; if (trustStore != null) { trustStore = getTolvenConfigWrapper().getTrustStore(oldPassword, trustStoreDetail); trustStoreFile = new File(trustStoreDetail.getSource()); } File tmpKey = null; File tmpKeyStore = null; File tmpTrustStore = null; boolean success = false; try { getTolvenConfigWrapper().getBuildDir().mkdirs(); tmpKey = new File(getTolvenConfigWrapper().getBuildDir(), keyFile.getName()); write(privateKey, keyDetail.getFormat(), tmpKey, newPassword); if (keyStoreFile != null) { tmpKeyStore = new File(getTolvenConfigWrapper().getBuildDir(), keyStoreFile.getName()); String alias = keyStore.aliases().nextElement(); Key key = keyStore.getKey(alias, oldPassword); Certificate[] chain = keyStore.getCertificateChain(alias); keyStore.setKeyEntry(alias, key, newPassword, chain); write(keyStore, tmpKeyStore, newPassword); } if (trustStoreFile != null) { tmpTrustStore = new File(getTolvenConfigWrapper().getBuildDir(), trustStoreFile.getName()); write(trustStore, tmpTrustStore, newPassword); } FileUtils.copyFile(tmpKey, keyFile); if (keyStoreFile != null) { FileUtils.copyFile(tmpKeyStore, keyStoreFile); } if (trustStoreFile != null) { FileUtils.copyFile(tmpTrustStore, trustStoreFile); } success = true; } finally { if (success) { if (tmpKey != null) { tmpKey.delete(); } if (tmpKeyStore != null) { tmpKeyStore.delete(); } if (tmpKeyStore != null) { tmpKeyStore.delete(); } getPasswordHolder().changePassword(passwordInfo, oldPassword, newPassword); } } }
From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java
/** * Method that generates the keys that will be used by the CAToken. * The method can be used to generate keys for an initial CA token or to renew Certificate signing keys. * If setstatustowaiting is true and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN. * If setstatustowaiting is false and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN_NEXT. * /*w ww.j a v a 2s .com*/ * @param authenticationCode the password used to encrypt the keystore, later needed to activate CA Token * @param renew flag indicating if the keys are renewed instead of created fresh. Renewing keys does not * create new encryption keys, since this would make it impossible to decrypt old stuff. * @param activate flag indicating if the new keys should be activated immediately or or they should be added as "next" signing key. * Using true here makes it possible to generate certificate renewal requests for external CAs still using the old keys until the response is received. */ public void generateKeys(final String authenticationCode, final boolean renew, final boolean activate) throws Exception { if (log.isTraceEnabled()) { log.trace(">generateKeys: " + (authenticationCode == null ? "null" : "hidden") + ", renew=" + renew + ", activate=" + activate); } CATokenInfo catokeninfo = getCATokenInfo(); // First we start by setting a new sequence for our new keys String oldSequence = getKeySequence(); log.debug("Current sequence: " + oldSequence); String newSequence = StringTools.incrementKeySequence(getCATokenInfo().getKeySequenceFormat(), oldSequence); // We store the sequence permanently in the object last, when we know everything went well // If we don't give an authentication code, perhaps we have autoactivation enabled char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode); String tokentype = null; // Then we can move on to actually generating the keys if (catokeninfo instanceof SoftCATokenInfo) { // If we have an existing soft keystore verify that the password is correct checkSoftKeystorePassword(authenticationCode); SoftCATokenInfo info = (SoftCATokenInfo) catokeninfo; Properties properties = getProperties(); PublicKey pubEnc = null; PrivateKey privEnc = null; PublicKey previousPubSign = null; PrivateKey previousPrivSign = null; PublicKey oldPreviousPubSign = null; PrivateKey oldPreviousPrivSign = null; if (!renew) { log.debug("We are generating initial keys."); // Generate encryption keys. // Encryption keys must be RSA still KeyPair enckeys = KeyTools.genKeys(info.getEncKeySpec(), info.getEncKeyAlgorithm()); pubEnc = enckeys.getPublic(); privEnc = enckeys.getPrivate(); } else { log.debug("We are renewing keys."); // Get the already existing encryption and signature keys ICAToken token = getCAToken(); pubEnc = token.getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); privEnc = token.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); previousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN); previousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN); oldPreviousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS); oldPreviousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS); } // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key // If the user did not specify this, we try to generate a key with the same specification as the currently used key. String keyspec = info.getSignKeySpec(); // can be "unknown" if (StringUtils.equals(keyspec, AlgorithmTools.KEYSPEC_UNKNOWN)) { keyspec = null; } AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(previousPubSign); if (log.isDebugEnabled()) { if (keyspec != null) { log.debug("Generating new Soft key with specified spec " + keyspec + " with label " + SoftCAToken.PRIVATESIGNKEYALIAS); } else { int keySize = KeyTools.getKeyLength(previousPubSign); String alg = previousPubSign.getAlgorithm(); log.debug("Generating new Soft " + alg + " key with spec " + paramspec + " (size=" + keySize + ") with label " + SoftCAToken.PRIVATESIGNKEYALIAS); } } // Generate signature keys. KeyPair newsignkeys = KeyTools.genKeys(keyspec, paramspec, info.getSignKeyAlgorithm()); // Create the new keystore and add the new signature keys KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // PLay with aliases depending on if we activate the new key or not String newSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS; String previousSignKeyAlias = SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS; if (!activate) { // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS) newSignKeyAlias = SoftCAToken.NEXTPRIVATESIGNKEYALIAS; previousSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS; } log.debug("Setting newsignkeys as " + newSignKeyAlias + " in soft CA token."); Certificate[] certchain = new Certificate[1]; // generate dummy certificate String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(newsignkeys.getPublic()).iterator() .next(); certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, newsignkeys.getPrivate(), newsignkeys.getPublic(), sigAlg, true); keystore.setKeyEntry(newSignKeyAlias, newsignkeys.getPrivate(), null, certchain); if (!activate) { log.debug("Set next sequence: " + newSequence); properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence); log.debug("Set nextCertSignKey: " + newSignKeyAlias); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newSignKeyAlias); } // If we have an old key (i.e. generating new keys), we will store the old one as "previous" if (previousPrivSign != null) { log.debug("Setting previousPrivSign as " + previousSignKeyAlias + " in soft CA token."); sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(previousPubSign).iterator().next(); certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, previousPrivSign, previousPubSign, sigAlg, true); keystore.setKeyEntry(previousSignKeyAlias, previousPrivSign, null, certchain); // Now this keystore should have this previous key if (activate) { // This key pair is now moved down to previous sign key properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, previousSignKeyAlias); // Set previous sequence so we can create link certificates log.debug("Set previous sequence : " + oldSequence); properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence); } else { // If we have an old previous key and we are not activating the new key, we will keep this one as "previous" // If the new keys are activate the old previous keys are trashed and replaced by the old active signature key String prevProp = properties.getProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS); // If we don't have a previous key don't try to add it if ((oldPreviousPrivSign != null) && (prevProp != null)) { log.debug("Setting old previousprivatesignkeyalias as " + SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS + " in soft CA token."); sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(oldPreviousPubSign).iterator() .next(); certchain[0] = CertTools.genSelfCert("CN=dummy3", 36500, null, oldPreviousPrivSign, oldPreviousPubSign, sigAlg, true); keystore.setKeyEntry(SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS, oldPreviousPrivSign, null, certchain); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS); } else { log.debug("No previousprivatesignkeyalias exists, not setting any previous key."); } } } // Finally install the old encryption/decryption keys as well sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(pubEnc).iterator().next(); certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, privEnc, pubEnc, sigAlg, true); keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, privEnc, null, certchain); storeSoftKeyStore(authCode, info, properties, keystore); tokentype = "Soft"; // for logging } else if (catokeninfo instanceof HardCATokenInfo) { ICAToken token = getCAToken(); if (token instanceof PKCS11CAToken) { Properties properties = getProperties(); PublicKey pubK = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN); String keyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CERTSIGN); log.debug("Old key label is: " + keyLabel); String crlKeyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CRLSIGN); // The key label to use for the new key // Remove the old sequence from the end of the key label and replace it with the // new label. If no label was present just concatenate the new label String newKeyLabel = StringUtils.removeEnd(keyLabel, oldSequence) + newSequence; log.debug("New key label is: " + newKeyLabel); final KeyStore.PasswordProtection pwp = new KeyStore.PasswordProtection(authCode); // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key // If the user did not specify this, we try to generate a key with the same specification as the currently used key. String keyspec = properties.getProperty(ICAToken.KEYSPEC_PROPERTY); // can be null, and that is ok AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(pubK); if (log.isDebugEnabled()) { String sharedLibrary = properties.getProperty(PKCS11CAToken.SHLIB_LABEL_KEY); String slot = properties.getProperty(PKCS11CAToken.SLOT_LABEL_KEY); String attributesFile = properties.getProperty(PKCS11CAToken.ATTRIB_LABEL_KEY); if (keyspec != null) { log.debug("Generating new PKCS#11 key with specified spec " + keyspec + " with label " + newKeyLabel + ", on slot " + slot + ", using sharedLibrary " + sharedLibrary + ", and attributesFile " + attributesFile); } else { int keySize = KeyTools.getKeyLength(pubK); String alg = pubK.getAlgorithm(); log.debug("Generating new PKCS#11 " + alg + " key with spec " + paramspec + " (size=" + keySize + ") with label " + newKeyLabel + ", on slot " + slot + ", using sharedLibrary " + sharedLibrary + ", and attributesFile " + attributesFile); } } KeyStoreContainer cont = KeyStoreContainerFactory .getInstance(KeyStoreContainer.KEYSTORE_TYPE_PKCS11, token.getProvider(), pwp); cont.setPassPhraseLoadSave(authCode); if (keyspec != null) { log.debug("Generating from string keyspec: " + keyspec); cont.generate(keyspec, newKeyLabel); } else { log.debug("Generating from AlgorithmParameterSpec: " + paramspec); cont.generate(paramspec, newKeyLabel); } // Set properties so that we will start using the new key, or not, depending on the activate argument KeyStrings kstr = new KeyStrings(properties); String certsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CERTSIGN); log.debug("CAKEYPURPOSE_CERTSIGN keystring is: " + certsignkeystr); String crlsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CRLSIGN); log.debug("CAKEYPURPOSE_CRLSIGN keystring is: " + crlsignkeystr); if (!activate) { // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS) log.debug("Set nextCertSignKey: " + newKeyLabel); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newKeyLabel); log.debug("Set next sequence: " + newSequence); properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence); } else { properties.setProperty(certsignkeystr, newKeyLabel); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, keyLabel); // If the key strings are not equal, i.e. crtSignKey and crlSignKey was used instead of just defaultKey // and the keys are the same. Then we need to set both keys to use the new key label if (!StringUtils.equals(certsignkeystr, crlsignkeystr) && StringUtils.equals(keyLabel, crlKeyLabel)) { log.debug("Also setting crlsignkeystr to " + newKeyLabel); properties.setProperty(crlsignkeystr, newKeyLabel); } // Also set the previous sequence properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence); } setProperties(properties); tokentype = "PKCS#11"; // for logging } } else { String msg = intres.getLocalizedMessage("catoken.genkeysnotavail"); log.error(msg); return; } // Store the new sequence permanently. We should not do this earlier, because if an error is thrown generating keys we should not have updated the CA token object if (activate) { log.debug("Setting new sequence: " + newSequence); setKeySequence(newSequence); } // Finally reset the token so it will be re-read when we want to use it this.catoken = null; String msg = intres.getLocalizedMessage("catoken.generatedkeys", tokentype); log.info(msg); if (log.isTraceEnabled()) { log.trace("<generateKeys"); } }
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"); }/*from ww w . j ava2 s. co m*/ 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:strat.mining.stratum.proxy.Launcher.java
/** * Check that a valid SSl certificate already exists. If not, create a new * one./*from ww w . j a va 2 s .c o m*/ * * @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: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"); }/* ww w.ja v a 2s. co m*/ 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: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 w w . j a v a 2 s .c o m*/ */ 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:org.globus.gsi.gssapi.GlobusGSSContextImpl.java
private void setCredential() throws GSSException { try {//from ww w . ja v a 2s . c o m /*DEL this.context.setCredential(this.ctxCred.getX509Credential()); */ KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); X509Credential cred = this.ctxCred.getX509Credential(); keyStore.setKeyEntry("default", cred.getPrivateKey(), "password".toCharArray(), cred.getCertificateChain()); this.sslConfigurator.setCredentialStore(keyStore); this.sslConfigurator.setCredentialStorePassword("password"); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
/** Creates a PKCS#12 KeyStore with keys only from an JKS file (no issuer certs or trusted certs) */ @Deprecated //Remove this method as soon as upgrading from 5->6 is dropped private KeyStore makeKeysOnlyP12(KeyStore keyStore, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, CertificateException, IOException { final KeyStore p12 = KeyStore.getInstance("PKCS12", "BC"); final KeyStore.ProtectionParameter protParam = (password != null ? new KeyStore.PasswordProtection(password) : null);//from w w w . j a v a 2 s . c om p12.load(null, password); // initialize final Enumeration<String> en = keyStore.aliases(); while (en.hasMoreElements()) { final String alias = en.nextElement(); if (!keyStore.isKeyEntry(alias)) continue; try { KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, protParam); Certificate[] chain = new Certificate[] { entry.getCertificate() }; p12.setKeyEntry(alias, entry.getPrivateKey(), password, chain); } catch (UnsupportedOperationException uoe) { KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null); Certificate[] chain = new Certificate[] { entry.getCertificate() }; p12.setKeyEntry(alias, entry.getPrivateKey(), null, chain); } } return p12; }