Example usage for java.security KeyStore store

List of usage examples for java.security KeyStore store

Introduction

In this page you can find the example usage for java.security KeyStore store.

Prototype

public final void store(OutputStream stream, char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Stores this keystore to the given output stream, and protects its integrity with the given password.

Usage

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

public byte[] convertKeystoreToBytes(final KeyStore keyStore, final String keyStorePwd) {
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {/*  w  w w  . j a  v a  2 s. c o  m*/
        keyStore.store(byteArrayOutputStream, keyStorePwd.toCharArray());
    } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
        LOG.error("Fatal error convert keystore to bytes", e);
    }
    return byteArrayOutputStream.toByteArray();
}

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);//from   w w  w .j a  v  a 2 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:org.ejbca.extra.db.PKCS12Response.java

/**
 * Default constructor that should be used.
 *  //from ww w. j a v a  2  s .  c  o m
 */
public PKCS12Response(long requestId, boolean success, String failinfo, KeyStore pkcs12, String password) {
    super(requestId, success, failinfo);
    try {
        data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE));
        data.put(VERSION, Float.valueOf(LATEST_VERSION));
        if (pkcs12 != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            pkcs12.store(baos, password.toCharArray());
            String keystorestring = new String(Base64.encode(baos.toByteArray()));
            baos.close();
            data.put(KEYSTORE, keystorestring);
        }
    } catch (Exception e) {
        log.error("KeyStore encoding failed", e);
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

public void exportKeystore(final KeyStore keystore, final String keystorePassword, final String fileName) {
    try (final FileOutputStream fOutputStream = new FileOutputStream(workingDir + fileName)) {
        keystore.store(fOutputStream, keystorePassword.toCharArray());
    } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
        LOG.error("Fatal error export keystore", e);
    }/*from www  .  j  ava2s. c om*/
}

From source file:org.apache.stratos.keystore.mgt.KeyStoreGenerator.java

/**
 * Persist the keystore in the gov.registry
 *
 * @param keyStore created Keystore of the tenant
 * @param PKCertificate pub. key of the tenant
 * @throws KeyStoreMgtException Exception when storing the keystore in the registry
 *///w w w.j a v  a2s .  c  o  m
private void persistKeyStore(KeyStore keyStore, X509Certificate PKCertificate) throws KeyStoreMgtException {
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        keyStore.store(outputStream, password.toCharArray());
        outputStream.flush();
        outputStream.close();

        String keyStoreName = generateKSNameFromDomainName();
        // Use the keystore using the keystore admin
        KeyStoreAdmin keystoreAdmin = new KeyStoreAdmin(tenantId, govRegistry);
        keystoreAdmin.addKeyStore(outputStream.toByteArray(), keyStoreName, password, " ", "JKS", password);

        //Create the pub. key resource
        Resource pubKeyResource = govRegistry.newResource();
        pubKeyResource.setContent(PKCertificate.getEncoded());
        pubKeyResource.addProperty(SecurityConstants.PROP_TENANT_PUB_KEY_FILE_NAME_APPENDER,
                generatePubKeyFileNameAppender());

        govRegistry.put(RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE, pubKeyResource);

        //associate the public key with the keystore
        govRegistry.addAssociation(RegistryResources.SecurityManagement.KEY_STORES + "/" + keyStoreName,
                RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE,
                SecurityConstants.ASSOCIATION_TENANT_KS_PUB_KEY);

    } catch (RegistryException e) {
        String msg = "Error when writing the keystore/pub.cert to registry";
        log.error(msg, e);
        throw new KeyStoreMgtException(msg, e);
    } catch (Exception e) {
        String msg = "Error when processing keystore/pub. cert to be stored in registry";
        log.error(msg, e);
        throw new KeyStoreMgtException(msg, e);
    }
}

From source file:net.sf.keystore_explorer.gui.dnd.DragKeyPairEntry.java

/**
 * Construct DragKeyPairEntry./*from w  w  w.  ja va2s.co  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:org.apache.directory.studio.connection.core.StudioKeyStoreManager.java

/**
 * Adds the certificate to the file key store.
 * //w ww . j a v a  2  s  . c o m
 * @param certificate the certificate
 */
private void addToFileKeyStore(X509Certificate certificate) throws CertificateException {
    try {
        KeyStore fileKeyStore = getFileKeyStore();
        addToKeyStore(certificate, fileKeyStore);
        File file = ConnectionCorePlugin.getDefault().getStateLocation().append(filename).toFile();
        fileKeyStore.store(new FileOutputStream(file), password.toCharArray());
    } catch (Exception e) {
        throw new CertificateException(Messages.StudioKeyStoreManager_CantAddCertificateToTrustStore, e);
    }
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

@Override
public void storeCertificate(KeyStore keystore, OutputStream os, String keystorePassword) throws CertException {
    try {/*from   w ww  .j ava2s.  c om*/
        keystore.store(os, keystorePassword.toCharArray());
    } catch (KeyStoreException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (CertificateException e) {
        throw new CertException(e);
    } catch (IOException e) {
        throw new CertException(e);
    }
}

From source file:org.apache.directory.studio.connection.core.StudioKeyStoreManager.java

/**
 * Removes the certificate from the file key store.
 * //  ww  w  . j  av  a 2 s . c  o  m
 * @param certificate the certificate
 */
private void removeFromFileKeyStore(X509Certificate certificate) throws CertificateException {
    try {
        KeyStore fileKeyStore = getFileKeyStore();
        removeFromKeyStore(certificate, fileKeyStore);
        File file = ConnectionCorePlugin.getDefault().getStateLocation().append(filename).toFile();
        fileKeyStore.store(new FileOutputStream(file), password.toCharArray());
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateException(Messages.StudioKeyStoreManager_CantRemoveCertificateFromTrustStore, e);
    }
}

From source file:org.wso2.carbon.keystore.mgt.KeyStoreGenerator.java

/**
 * Persist the trust store in the gov.registry
 *
 * @param trustStore created trust store of the tenant
 * @throws KeyStoreMgtException Exception when storing the trust store in the registry
 *//* w w  w  .  j a  v  a2s.  co m*/
private void persistTrustStore(KeyStore trustStore, String trustStoreName) throws KeyStoreMgtException {
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        trustStore.store(outputStream, password.toCharArray());
        outputStream.flush();
        outputStream.close();

        KeyStoreAdmin keystoreAdmin = new KeyStoreAdmin(tenantId, govRegistry);
        keystoreAdmin.addTrustStore(outputStream.toByteArray(), trustStoreName, password, " ", "JKS");
    } catch (Exception e) {
        String msg = "Error when processing keystore/pub. cert to be stored in registry";
        log.error(msg, e);
        throw new KeyStoreMgtException(msg, e);
    }
}