Example usage for java.security KeyStore getInstance

List of usage examples for java.security KeyStore getInstance

Introduction

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

Prototype

public static final KeyStore getInstance(File file, LoadStoreParameter param)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Returns a loaded keystore object of the appropriate keystore type.

Usage

From source file:com.aqnote.shared.cryptology.cert.util.KeyStoreUtil.java

public static KeyStore getPKCS12KeyStore(String alias, Certificate[] certChain, KeyPair keyPair, char[] passwd)
        throws Exception {

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) keyPair.getPrivate();
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
    SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic());
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, pubKeyId);
    KeyStore store = KeyStore.getInstance(KEY_STORE_TYPE, JCE_PROVIDER);
    store.load(null, null);/* w  ww.  j ava 2  s  . c  o  m*/
    store.setKeyEntry(alias, keyPair.getPrivate(), passwd, certChain);
    return store;
}

From source file:be.fedict.hsm.model.KeyStoreLoaderBean.java

private Map<String, PrivateKeyEntry> loadPKCS11(KeyStoreEntity keyStoreEntity) throws KeyStoreException,
        IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
    File tmpConfigFile = File.createTempFile("pkcs11-", ".conf");
    tmpConfigFile.deleteOnExit();//from   w  ww  .  j  av a2s. com
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile));
    configWriter.println("name=HSM-" + keyStoreEntity.getId());
    String path = keyStoreEntity.getPath();
    LOG.debug("PKCS11 path: " + path);
    LOG.debug("slot list index: " + keyStoreEntity.getSlotListIndex());
    configWriter.println("library=" + path);
    configWriter.println("slotListIndex=" + keyStoreEntity.getSlotListIndex());
    configWriter.close();
    SunPKCS11 sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    LOG.debug("adding SunPKCS11 JCA provider: " + sunPKCS11.getName());
    /*
     * Reloads also need to work properly.
     */
    Security.removeProvider(sunPKCS11.getName());
    Security.addProvider(sunPKCS11);
    KeyStore keyStore = KeyStore.getInstance("PKCS11", sunPKCS11);
    if (null != keyStoreEntity.getPassword()) {
        keyStore.load(null, keyStoreEntity.getPassword().toCharArray());
    } else {
        keyStore.load(null, null);
    }
    String keyStorePassword = keyStoreEntity.getPassword();
    return loadKeys(keyStoreEntity, keyStore, keyStorePassword);
}

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ?//from  w  w  w. j  a  va2  s.co m
 * 
 * @param type
 *            
 * @param inputStream
 *            ?
 * @param password
 *            ?
 * @return 
 */
public static Key getKey(String type, InputStream inputStream, String password) {
    Assert.isNotEmpty(type);
    Assert.notNull(inputStream);

    try {
        KeyStore keyStore = KeyStore.getInstance(type, PROVIDER);
        keyStore.load(inputStream, password != null ? password.toCharArray() : null);
        String alias = keyStore.aliases().hasMoreElements() ? keyStore.aliases().nextElement() : null;
        return keyStore.getKey(alias, password != null ? password.toCharArray() : null);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.microsoft.aad.adal4j.AsymmetricKeyCredential.java

/**
 * Static method to create KeyCredential instance.
 * //from  w  w  w  .ja v  a  2 s  .c o m
 * @param clientId
 *            Identifier of the client requesting the token.
 * @param pkcs12Certificate
 *            PKCS12 certificate stream containing public and private key.
 *            Caller is responsible for handling the input stream.
 * @param password
 *            certificate password
 * @return KeyCredential instance
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws UnrecoverableKeyException
 */
public static AsymmetricKeyCredential create(final String clientId, final InputStream pkcs12Certificate,
        final String password) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException,
        CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException {
    final KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
    keystore.load(pkcs12Certificate, password.toCharArray());
    final Enumeration<String> aliases = keystore.aliases();
    final String alias = aliases.nextElement();
    final PrivateKey key = (PrivateKey) keystore.getKey(alias, password.toCharArray());
    final X509Certificate publicCertificate = (X509Certificate) keystore.getCertificate(alias);
    return create(clientId, key, publicCertificate);
}

From source file:eidassaml.starterkit.Utils.java

/**
 * //w w w .j  a v  a 2  s.  c  o  m
 * @param stream
 * @param password
 * @param alias
 * @return
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws IOException
 * @throws UnrecoverableKeyException
 * @throws NoSuchProviderException 
 */
public static X509KeyPair ReadPKCS12(InputStream stream, char[] password, String alias)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException, NoSuchProviderException {
    KeyStore p12 = KeyStore.getInstance("pkcs12", "BC");
    p12.load(stream, password);
    Enumeration<String> e = p12.aliases();
    PrivateKey key = null;
    X509Certificate cert = null;
    StringBuffer aliasBuf = new StringBuffer();
    while (e.hasMoreElements()) {
        String currentalias = (String) e.nextElement();
        aliasBuf.append(currentalias);
        aliasBuf.append(" ||| ");
        cert = (X509Certificate) p12.getCertificate(currentalias);
        key = (PrivateKey) p12.getKey(currentalias, password);
        if (Utils.IsNullOrEmpty(alias) && key != null) {
            //take the first one
            break;
        } else if (currentalias.equals(alias) && key != null) {
            break;
        }
    }
    if (key != null) {
        return new X509KeyPair(key, cert);
    } else {
        StringBuffer errbuf = new StringBuffer();
        errbuf.append("keystore does not contains alias " + alias + ". Try alias " + aliasBuf.toString());
        throw new KeyStoreException(errbuf.toString());
    }

}

From source file:com.aqnote.shared.cryptology.cert.util.KeyStoreUtil.java

public static KeyStore readPKCS12KeyStore(String alias, Certificate[] chain, KeyPair keyPair, char[] pwd)
        throws Exception {
    PKCS12SafeBagBuilder BagBuilder = new JcaPKCS12SafeBagBuilder((X509Certificate) chain[0]);
    BagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(alias));
    SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic());
    BagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

    KeyStore store = KeyStore.getInstance(KEY_STORE_TYPE, JCE_PROVIDER);
    store.load(null, null);//from  ww  w .j av a  2s .c om
    store.setKeyEntry(alias, keyPair.getPrivate(), pwd, chain);

    return store;
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static X500Name getInfo(File keystore) {
    try {/*  w w w. j  a v a 2  s  .  c om*/
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        FileInputStream stream = new FileInputStream(keystore);
        ks.load(stream, SECRET);
        IOUtils.closeQuietly(stream);
        X509CertImpl x509Cert = (X509CertImpl) ks.getCertificate(ALIAS);
        return (X500Name) x509Cert.getSubjectDN();
    } catch (Exception e) {
        return null;
    }
}

From source file:com.microsoft.aad.adal4j.MSCAPIAsymmetricKeyCredential.java

/**
 * Static method to create KeyCredential instance.
 * // w  w  w.  j av  a  2  s.  c o  m
 * @param clientId
 *            Identifier of the client requesting the token.
 * @param pkcs12Certificate
 *            PKCS12 certificate stream containing public and private key.
 *            Caller is responsible to handling the inputstream.
 * @param password
 *            certificate password
 * @return KeyCredential instance
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws UnrecoverableKeyException
 */
public static MSCAPIAsymmetricKeyCredential create(final String clientId, final InputStream pkcs12Certificate,
        final String password) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException,
        CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException {
    final KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
    keystore.load(pkcs12Certificate, password.toCharArray());
    final Enumeration<String> aliases = keystore.aliases();
    final String alias = aliases.nextElement();
    final PrivateKey key = (PrivateKey) keystore.getKey(alias, password.toCharArray());
    final X509Certificate publicCertificate = (X509Certificate) keystore.getCertificate(alias);
    return create(clientId, key, publicCertificate);
}

From source file:org.jasig.portal.security.provider.saml.SSLSecurityImpl.java

private void setSSLClientCredentials(PrivateKey pk, Certificate cert) throws KeyStoreException,
        NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException {
    this.logger.info("Private key: [{}].", pk.toString());
    this.logger.info("Certificate: [{}].", cert.toString());
    KeyStore ks = KeyStore.getInstance("JKS", "SUN");
    ks.load(null, null);/*from   ww  w  .j av  a  2 s  . c  o m*/
    Certificate[] certificates = new Certificate[1];
    certificates[0] = cert;
    String keystorePass = UUID.randomUUID().toString();
    ks.setKeyEntry("sp", pk, keystorePass.toCharArray(), certificates);
    this.keyStore = ks;
    this.keyStorePass = keystorePass;
}