Example usage for java.security KeyStore getEntry

List of usage examples for java.security KeyStore getEntry

Introduction

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

Prototype

public final Entry getEntry(String alias, ProtectionParameter protParam)
        throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException 

Source Link

Document

Gets a keystore Entry for the specified alias with the specified protection parameter.

Usage

From source file:net.link.util.common.KeyUtils.java

public static PrivateKeyEntry loadFirstPrivateKeyEntry(String keystoreType, InputStream keyStoreInputStream,
        char[] keyStorePassword, char[] keyEntryPassword) {

    /* Find the keystore. */
    KeyStore keyStore = loadKeyStore(keystoreType, keyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases;
    try {// w w  w . j a  va2 s.c  om
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("could not get aliases", e);
    }
    String alias = null;
    while (aliases.hasMoreElements()) {
        alias = aliases.nextElement();
        try {
            if (keyStore.isKeyEntry(alias))
                break;
        } catch (KeyStoreException e) {
            throw new InternalInconsistencyException(e);
        }

        alias = null;
    }
    if (alias == null)
        throw new InternalInconsistencyException("no private key found in keystore");

    /* Get the private key entry. */
    try {
        return (PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(keyEntryPassword));
    } catch (UnrecoverableEntryException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    }
}

From source file:com.gnut3ll4.android.basicandroidkeystore.MainActivity.java

public PrivateKey loadPrivateKey(String alias) throws KeyStoreException, CertificateException,
        NoSuchAlgorithmException, IOException, UnrecoverableEntryException {

    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);//from   ww w . j  a v a2 s. c o  m
    final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(ALIAS, null);
    return entry.getPrivateKey();
}

From source file:com.trsst.Command.java

public static final KeyPair readKeyPairFromFile(String alias, File file, char[] pwd) {
    FileInputStream input = null;
    try {//from w  w w.j av  a  2  s  .  c o m
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        input = new FileInputStream(file);
        keyStore.load(new FileInputStream(file), pwd);
        input.close();

        KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
                new KeyStore.PasswordProtection(pwd));
        PrivateKey privateKey = pkEntry.getPrivateKey();
        PublicKey publicKey = pkEntry.getCertificate().getPublicKey();
        return new KeyPair(publicKey, privateKey);
    } catch (/* javax.crypto.BadPaddingException */IOException bpe) {
        log.error("Passphrase could not decrypt key: " + bpe.getMessage());
    } catch (Throwable e) {
        log.error("Unexpected error while reading key: " + e.getMessage(), e);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                // ignore while closing
                log.trace("Error while closing: " + e.getMessage(), e);
            }
        }
    }
    return null;
}

From source file:RGSDigestTools.SignatureTool.java

/**
 * Init keys with private and public key from keystore
 * @param pKeyStorePath/* w ww .  j a  v a2 s  . c  o m*/
 * @param pKeyStorePasswd
 * @param pDSAlias
 * @param pPrivKeyPasswd
 * @param pCheckDSAlias
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws UnrecoverableEntryException 
 */
public void initKeysWithKeystore(String pKeyStorePath, String pKeyStorePasswd, String pDSAlias,
        String pPrivKeyPasswd, String pCheckDSAlias) throws KeyStoreException, CertificateException,
        NoSuchAlgorithmException, IOException, UnrecoverableEntryException {
    KeyStore ks = TrustStoreLoader.loadKeyStore(pKeyStorePath, pKeyStorePasswd);
    KeyStore.PasswordProtection passProtection = new KeyStore.PasswordProtection(pPrivKeyPasswd.toCharArray());
    KeyStore.PrivateKeyEntry DSKeyEnt = (KeyStore.PrivateKeyEntry) ks.getEntry(pDSAlias, passProtection);
    KeyStore.PrivateKeyEntry CheckDSKeyEnt = (KeyStore.PrivateKeyEntry) ks.getEntry(pCheckDSAlias,
            passProtection);

    this.signKey = DSKeyEnt.getPrivateKey();
    this.verifyKey = CheckDSKeyEnt.getCertificate().getPublicKey();

}

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

public Registration createAgentCertificate(final File authorityKeystore, String agentHostname) {
    Date epoch = new Date(0);
    KeyPair agentKeyPair = generateKeyPair();
    try {/*from  w ww .j  ava2 s  .c  o m*/
        KeyStore store = loadOrCreateCAKeyStore(authorityKeystore);
        KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store
                .getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY));

        X509Certificate[] chain = new X509Certificate[3];
        chain[2] = (X509Certificate) store.getCertificate("ca-cert");
        chain[1] = (X509Certificate) intermediateEntry.getCertificate();
        chain[0] = createAgentCertificate(agentKeyPair.getPublic(), intermediateEntry.getPrivateKey(),
                chain[1].getPublicKey(), agentHostname, epoch);
        return new Registration(agentKeyPair.getPrivate(), chain);
    } catch (Exception e) {
        throw bomb("Couldn't create agent certificate", e);
    }
}

From source file:RGSDigestTools.SignatureTool.java

/**
 * Init keys with private key from keystore and pubkey from resource
 * @param pKeyStorePath//ww w  .j  a va2s  .  com
 * @param pKeyStorePasswd
 * @param pDSAlias
 * @param pPrivKeyPasswd
 * @param PubkeyResource 
 * @throws java.security.KeyStoreException 
 * @throws java.security.cert.CertificateException 
 * @throws java.security.NoSuchAlgorithmException 
 * @throws java.io.IOException 
 * @throws java.security.UnrecoverableEntryException 
 * @throws java.security.spec.InvalidKeySpecException 
 */
public void initKeysWithKeystoreAndFile(String pKeyStorePath, String pKeyStorePasswd, String pDSAlias,
        String pPrivKeyPasswd, String PubkeyResource) throws KeyStoreException, CertificateException,
        NoSuchAlgorithmException, IOException, UnrecoverableEntryException, InvalidKeySpecException {
    KeyStore ks = TrustStoreLoader.loadKeyStore(pKeyStorePath, pKeyStorePasswd);
    KeyStore.PasswordProtection passProtection = new KeyStore.PasswordProtection(pPrivKeyPasswd.toCharArray());
    KeyStore.PrivateKeyEntry DSKeyEnt = (KeyStore.PrivateKeyEntry) ks.getEntry(pDSAlias, passProtection);

    this.signKey = DSKeyEnt.getPrivateKey();

    InputStream is = SignatureTool.class.getResourceAsStream(PubkeyResource);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int read = is.read();
    while (read != -1) {
        baos.write(read);
        read = is.read();
    }

    byte[] keyBytes = baos.toByteArray();
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    this.verifyKey = keyFactory.generatePublic(spec);
}

From source file:org.xwiki.contrib.encryption.internal.DefaultEncryptionTool.java

private SecretKeySpec retrieveEncryptionKey(KeyStore ks) {
    String protection = ENCRYPTION_KEY_PROTECTION;
    try {//from   w w w.j av a  2  s  .c o m
        logger.debug("Start retrieving password");
        KeyStore.SecretKeyEntry pkEntry = (KeyStore.SecretKeyEntry) ks.getEntry("encryptionKey",
                new KeyStore.PasswordProtection(protection.toCharArray()));
        SecretKeySpec mySecretKey = (SecretKeySpec) pkEntry.getSecretKey();
        return mySecretKey;
    } catch (Exception e) {
        logger.warn("Exception encountered while trying to retrieve the password : " + e.getMessage());
        return null;
    }
}

From source file:be.fedict.trust.service.KeyStoreUtils.java

public static PrivateKeyEntry loadPrivateKeyEntry(KeyStoreType type, String path, String storePassword,
        String entryPassword, String alias) throws KeyStoreLoadException {

    LOG.debug("load keystore");
    InputStream keyStoreStream = null;

    if (type.equals(KeyStoreType.PKCS11)) {
        Security.addProvider(new SunPKCS11(path));
    } else {//  w  ww  .j a v  a  2  s . c om
        try {
            keyStoreStream = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            throw new KeyStoreLoadException("Can't load keystore from config-specified location: " + path, e);
        }
    }

    /* Find the keystore. */
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(type.name());
    } catch (Exception e) {
        throw new KeyStoreLoadException("keystore instance not available: " + e.getMessage(), e);
    }

    /* Open the keystore and find the key entry. */
    try {
        keyStore.load(keyStoreStream, storePassword.toCharArray());
    } catch (Exception e) {
        throw new KeyStoreLoadException("keystore load error: " + e.getMessage(), e);
    }
    Enumeration<String> aliases;
    try {
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new KeyStoreLoadException("could not get aliases: " + e.getMessage(), e);
    }
    if (!aliases.hasMoreElements()) {
        throw new KeyStoreLoadException("keystore is empty");
    }
    if (null == alias || alias.isEmpty()) {
        alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
    }

    try {
        if (!keyStore.isKeyEntry(alias))
            throw new KeyStoreLoadException("not key entry: " + alias);
    } catch (KeyStoreException e) {
        throw new KeyStoreLoadException("key store error: " + e.getMessage(), e);
    }

    /* Get the private key entry. */
    try {
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry(alias,
                new KeyStore.PasswordProtection(entryPassword.toCharArray()));
        return privateKeyEntry;
    } catch (Exception e) {
        throw new KeyStoreLoadException("error retrieving key: " + e.getMessage(), e);
    }
}

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

boolean verifySigned(File keystore, Certificate agentCertificate) {
    try {// www.  j  a  v a2 s.c o m
        KeyStore store = KeyStore.getInstance("JKS");
        FileInputStream inputStream = new FileInputStream(keystore);
        store.load(inputStream, PASSWORD_AS_CHAR_ARRAY);
        IOUtils.closeQuietly(inputStream);
        KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store
                .getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY));
        Certificate intermediateCertificate = intermediateEntry.getCertificate();
        agentCertificate.verify(intermediateCertificate.getPublicKey());
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

protected SecretKey getSecretKey(String username, char[] password) {
    try {//w  ww .  java  2 s  . c  o m
        KeyStore store = getKeyStore(username, password);
        SecretKeyEntry entry = (SecretKeyEntry) store.getEntry(username,
                new KeyStore.PasswordProtection(password));
        return entry.getSecretKey();
    } catch (Exception ex) {
        // TODO: better exception handling
        throw new RuntimeException(ex);
    }
}