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:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java
/** * Creates a keystore with a single key and saves it to a file. * * @param file String file to save/* ww w .j av a 2 s .c o m*/ * @param ksPassword String store password to set on keystore * @param keyPassword String key password to set on key * @param alias String alias to use for the key * @param privateKey Key to save in keystore * @param cert Certificate to use as certificate chain associated to key * @throws GeneralSecurityException for any error with the security APIs * @throws IOException if there is an I/O error saving the file */ private static void createKeyStore(File file, String ksPassword, String keyPassword, String alias, Key privateKey, Certificate cert) throws GeneralSecurityException, IOException { KeyStore ks = createEmptyKeyStore(); ks.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), new Certificate[] { cert }); saveKeyStore(ks, file, ksPassword); }
From source file:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java
private static void createKeyStoreTrustStore(final KeyStore keyStore, final KeyStore trustStore) throws KeyStoreException { final X500Principal principal = new X500Principal(SERVER_DNS_STRING); final SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey .builder().setKeyAlgorithmName("RSA").setSignatureAlgorithmName("SHA1withRSA").setDn(principal) .setKeySize(1024).build();/*from w w w .j a va 2 s . c o m*/ final X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); keyStore.setKeyEntry(ALIAS, selfSignedX509CertificateAndSigningKey.getSigningKey(), KEYSTORE_CREATION_PASSWORD, new X509Certificate[] { certificate }); trustStore.setCertificateEntry(ALIAS, certificate); }
From source file:org.pepstock.jem.node.security.keystore.KeyStoreUtil.java
/** * Generate an empty key store where will be store the X509 certificate of * the user//from ww w . j a v a 2s .c o m * <p> * This key store will be used when the client will used a private key to * connect to the cluster and the cluster will used the relative public key * present in the x509 certificate to verify the identity of the client. * @param keystoreInfo entity with information about keystore * @throws KeyStoreException if any exception occurs during key store creation * */ public static void generate(KeyStoreInfo keystoreInfo) throws KeyStoreException { try { // if the keystore exist load it else create a new one KeyStore keystore = null; if (keystoreInfo.getFile().exists()) { keystore = getKeystore(keystoreInfo); } else { keystore = KeyStore.getInstance(keystoreInfo.getType()); keystore.load(null, null); save(keystore, keystoreInfo); } // if the keystore does not contain the given alias, create a new key // with that alias otherwise does nothing if (keystoreInfo.getSymmetricKeyAlias() != null && keystoreInfo.getSymmetricKeyPwd() != null && keystore.getKey(keystoreInfo.getSymmetricKeyAlias(), keystoreInfo.getSymmetricKeyPwd().toCharArray()) == null) { // creates simmetricKey Key secretKey = Crypto.generateSymmetricKey(); // adds the key keystore.setKeyEntry(keystoreInfo.getSymmetricKeyAlias(), secretKey, keystoreInfo.getSymmetricKeyPwd().toCharArray(), null); // saves the keystore save(keystore, keystoreInfo); } } catch (UnrecoverableKeyException e) { throw new KeyStoreException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new KeyStoreException(e.getMessage(), e); } catch (CertificateException e) { throw new KeyStoreException(e.getMessage(), e); } catch (IOException e) { throw new KeyStoreException(e.getMessage(), e); } }
From source file:com.ibm.iotf.client.AbstractClient.java
static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile, final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException { Security.addProvider(new BouncyCastleProvider()); X509Certificate caCert = null; if (caCrtFile != null) { // load CA certificate PEMReader reader = new PEMReader( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile))))); caCert = (X509Certificate) reader.readObject(); reader.close();/*w w w .j a v a 2 s. co m*/ } else { ClassLoader classLoader = AbstractClient.class.getClassLoader(); PEMReader reader = new PEMReader( new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream())); caCert = (X509Certificate) reader.readObject(); reader.close(); } PEMReader reader = new PEMReader( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile))))); X509Certificate cert = (X509Certificate) reader.readObject(); reader.close(); // load client private key reader = new PEMReader( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile))))); KeyPair key = (KeyPair) reader.readObject(); reader.close(); TrustManagerFactory tmf = null; if (caCert != null) { // CA certificate is used to authenticate server KeyStore caKs = KeyStore.getInstance("JKS"); //caKs.load(null, null); caKs.load(null, null); caKs.setCertificateEntry("ca-certificate", caCert); tmf = TrustManagerFactory.getInstance("PKIX"); tmf.init(caKs); } // client key and certificates are sent to server so it can authenticate us KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); ks.setCertificateEntry("certificate", cert); ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { cert }); KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX"); kmf.init(ks, password.toCharArray()); // finally, create SSL socket factory SSLContext context = SSLContext.getInstance("TLSv1.2"); if (tmf != null) { context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); } else { context.init(kmf.getKeyManagers(), null, null); } return context.getSocketFactory(); }
From source file:com.arm.connector.bridge.core.Utils.java
public static String createKeystore(ErrorLogger logger, String base, String sep, String filename, X509Certificate cert, PrivateKey priv_key, String pw) { String basedir = base + File.separator + sep; String keystore_filename = basedir + File.separator + filename; try {/*w ww .jav a2 s . c o m*/ // first create the directory if it does not exist File file = new File(basedir); // make the directories logger.info("createKeystore: Making directories for keystore..."); file.mkdirs(); // create the KeyStore logger.info("createKeystore: Creating keystore: " + keystore_filename); file = new File(keystore_filename); if (file.createNewFile()) { logger.info("createKeystore: keystore created: " + keystore_filename); } else { logger.warning("createKeystore: keystore already exists " + keystore_filename); } // store data into the keystore KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, pw.toCharArray()); // set the certificate, priv and pub keys if (cert != null) { Certificate[] cert_list = new Certificate[2]; cert_list[0] = cert; cert_list[1] = Utils.createCACertificate(logger); ks.setCertificateEntry("aws", cert_list[0]); ks.setCertificateEntry("verisign", cert_list[1]); if (priv_key != null) { try { ks.setKeyEntry("privkey", priv_key, pw.toCharArray(), cert_list); } catch (Exception ex2) { logger.warning("createKeystore: Exception during priv addition... not added to keystore", ex2); } } else { logger.warning("createKeystore: privkey is NULL... not added to keystore"); } } else { logger.warning("createKeystore: certificate is NULL... not added to keystore"); } try (FileOutputStream fos = new FileOutputStream(keystore_filename)) { // store away the keystore content ks.store(fos, pw.toCharArray()); // close fos.flush(); } } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException ex) { logger.warning("createKeystore: Unable to create keystore: " + keystore_filename, ex); } // return the keystore filename return keystore_filename; }
From source file:net.sf.hajdbc.codec.crypto.CipherCodecFactoryTest.java
@Before public void before() throws Exception { File file = File.createTempFile("ha-jdbc", "keystore"); SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM); this.key = factory.generateSecret(new DESKeySpec(Base64.decodeBase64(KEY.getBytes()))); KeyStore store = KeyStore.getInstance(CipherCodecFactory.Property.KEYSTORE_TYPE.defaultValue); store.load(null, null);/* w w w .j a va2 s .c o m*/ store.setKeyEntry(CipherCodecFactory.Property.KEY_ALIAS.defaultValue, this.key, KEY_PASSWORD.toCharArray(), null); FileOutputStream out = new FileOutputStream(file); try { store.store(out, STORE_PASSWORD.toCharArray()); } finally { Resources.close(out); } System.setProperty(CipherCodecFactory.Property.KEYSTORE_FILE.name, file.getPath()); System.setProperty(CipherCodecFactory.Property.KEYSTORE_PASSWORD.name, STORE_PASSWORD); System.setProperty(CipherCodecFactory.Property.KEY_PASSWORD.name, KEY_PASSWORD); }
From source file:net.sf.keystore_explorer.gui.dnd.DragKeyPairEntry.java
/** * Construct DragKeyPairEntry.//w ww .j a va 2 s .c o m * * @param name * Entry name * @param privateKey * Private key * @param password * Private key password * @param certificateChain * Certificate chain * @throws CryptoException * If there was a problem creating the content */ public DragKeyPairEntry(String name, PrivateKey privateKey, Password password, Certificate[] certificateChain) throws CryptoException { super(name); try { // Binary content is PKCS #12 protected by password KeyStore p12 = KeyStoreUtil.create(KeyStoreType.PKCS12); p12.setKeyEntry(name, privateKey, new char[] {}, certificateChain); ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); p12.store(baos, password.toCharArray()); contentBytes = baos.toByteArray(); } finally { IOUtils.closeQuietly(baos); } /* * String content is PKCS #8 PEM (private key) protected by PBE * (SHA-1 and 128 bit RC4) concatenated with PCKS #7 PEM * (certificate chain) */ StringBuffer sbContent = new StringBuffer(); String pkcs8 = Pkcs8Util.getEncryptedPem(privateKey, Pkcs8PbeType.SHA1_128BIT_RC4, password); String pkcs7 = X509CertUtil.getCertsEncodedPkcs7Pem(X509CertUtil.convertCertificates(certificateChain)); // Output notes delimiting the different parts sbContent.append(res.getString("DragKeyPairEntry.StringFlavor.PrivateKeyPart.text")); sbContent.append("\n\n"); sbContent.append(pkcs8); sbContent.append('\n'); sbContent.append(res.getString("DragKeyPairEntry.StringFlavor.CertificateChainPart.text")); sbContent.append("\n\n"); sbContent.append(pkcs7); contentStr = sbContent.toString(); // Get drag image image = new ImageIcon(Toolkit.getDefaultToolkit() .createImage(getClass().getResource(res.getString("DragKeyPairEntry.Drag.image")))); } catch (IOException ex) { throw new CryptoException(res.getString("NoGetKeyPairEntryContent.exception.message"), ex); } catch (GeneralSecurityException ex) { throw new CryptoException(res.getString("NoGetKeyPairEntryContent.exception.message"), ex); } }
From source file:com.thoughtworks.go.security.KeyStoreManager.java
public void storeCertificate(String friendlyName, File storeFile, String passwd, Registration entry) throws Exception { KeyStore storeToSave = loadOrEmpty(storeFile, passwd); bombIfNull(storeToSave, "Store not yet initialized"); storeToSave.setKeyEntry(friendlyName, entry.getPrivateKey(), passwd.toCharArray(), entry.getChain()); writeStore(storeToSave, storeFile, passwd); }
From source file:org.metaeffekt.dcc.agent.AuthenticationKeyGenerator.java
private void createKeyStore(File file, String keyAlias, KeyPair key, X509Certificate certificate, char[] password) throws GeneralSecurityException, IOException { final KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE); keyStore.load(null, password);/*from www .ja v a 2 s . co m*/ keyStore.setKeyEntry(keyAlias, key.getPrivate(), password, new Certificate[] { certificate }); persistKeyStore(keyStore, file, password); }
From source file:org.ejbca.util.keystore.KeyTools.java
/** * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is * set to 'privateKey' and the private key password is null. * * @param alias the alias used for the key entry * @param privKey RSA private key//from w ww. j a v a 2 s .c om * @param cert user certificate * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'. * @return KeyStore containing PKCS12-keystore * @exception Exception if input parameters are not OK or certificate generation fails */ public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert, final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException { if (log.isTraceEnabled()) { log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } // Certificate chain if (cert == null) { throw new IllegalArgumentException("Parameter cert cannot be null."); } int len = 1; if (cachain != null) { len += cachain.length; } final Certificate[] chain = new Certificate[len]; // To not get a ClassCastException we need to generate a real new certificate with BC final CertificateFactory cf = CertTools.getCertificateFactory(); chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded())); if (cachain != null) { for (int i = 0; i < cachain.length; i++) { final X509Certificate tmpcert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded())); chain[i + 1] = tmpcert; } } if (chain.length > 1) { for (int i = 1; i < chain.length; i++) { final X509Certificate cacert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded())); // Set attributes on CA-cert try { final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i]; // We construct a friendly name for the CA, and try with some parts from the DN if they exist. String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN"); // On the ones below we +i to make it unique, O might not be otherwise if (cafriendly == null) { cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i; } if (cafriendly == null) { cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i); } if (cafriendly == null) { cafriendly = "CA_unknown" + i; } caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(cafriendly)); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } } } // Set attributes on user-cert try { final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0]; certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); // in this case we just set the local key id to that of the public key certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(chain[0].getPublicKey())); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } // "Clean" private key, i.e. remove any old attributes final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC"); final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded())); // Set attributes for private key try { final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk; // in this case we just set the local key id to that of the public key keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(chain[0].getPublicKey())); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } // store the key and the certificate chain final KeyStore store = KeyStore.getInstance("PKCS12", "BC"); store.load(null, null); store.setKeyEntry(alias, pk, null, chain); if (log.isTraceEnabled()) { log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } return store; }