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:mitm.common.tools.SMIME.java

private static void sign(MimeMessage source, KeyStore keyStore, String alias, String password,
        String digestAlgo, String outFile) throws Exception {
    if (StringUtils.isEmpty(alias)) {
        throw new MissingArgumentException("alias is missing.");
    }// ww  w  . ja v  a  2  s.c o m

    KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));

    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        throw new KeyStoreException("Key is not a PrivateKeyEntry.");
    }

    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry;

    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    PrivateKey key = privateKeyEntry.getPrivateKey();

    if (certificate == null) {
        throw new KeyStoreException("Entry does not have a certificate.");
    }

    if (key == null) {
        throw new KeyStoreException("Entry does not have a private key.");
    }

    SMIMESigningAlgorithm signingAlgorithm;

    if (StringUtils.isNotEmpty(digestAlgo)) {
        signingAlgorithm = SMIMESigningAlgorithm.fromName(digestAlgo);

        if (signingAlgorithm == null) {
            throw new IllegalArgumentException(digestAlgo + " is not a valid digest.");
        }
    } else {
        signingAlgorithm = SMIMESigningAlgorithm.SHA1WITHRSA;
    }

    SMIMEBuilder builder = new SMIMEBuilderImpl(source);

    builder.addCertificates(certificate);
    builder.addSigner(key, certificate, signingAlgorithm);

    builder.sign(SMIMESignMode.CLEAR);

    MimeMessage signed = builder.buildMessage();

    if (signed == null) {
        throw new SMIMEException("Message could not be signed");
    }

    MailUtils.writeMessage(signed, new File(outFile));
}

From source file:net.theblackchamber.crypto.util.KeystoreUtils.java

/**
* Method which will load a secret key from an input stream with the specified entry
* name./*from   w  w w. j av a  2s.co m*/
* 
* @param keystore {@link KeyStore} file to read.
* @param entryName Entry name of the key to be retrieved
* @param keyStorePassword Password used to open the {@link KeyStore}
* @return
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws CertificateException
* @throws IOException
* @throws UnrecoverableEntryException
*/
public static SecretKey getAESSecretKey(InputStream keyInputStream, String entryName, String keyStorePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableEntryException {
    KeyStore keyStore = KeyStore.getInstance("JCEKS");

    if (keyInputStream == null) {
        throw new KeyStoreException("No Keystore stream provided.");
    }
    if (StringUtils.isEmpty(keyStorePassword)) {
        throw new KeyStoreException("No Keystore password provided.");
    }
    if (StringUtils.isEmpty(entryName)) {
        throw new KeyStoreException("No Keystore entry name provided.");
    }

    keyStore.load(keyInputStream, keyStorePassword.toCharArray());
    KeyStore.ProtectionParameter protectionParameter = new KeyStore.PasswordProtection(
            keyStorePassword.toCharArray());
    KeyStore.SecretKeyEntry pkEntry = (KeyStore.SecretKeyEntry) keyStore.getEntry(entryName,
            protectionParameter);
    try {
        return pkEntry.getSecretKey();
    } finally {
        keyInputStream.close();
    }

}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Fetch private key from KeyStore/*from  ww w.  j a v a2s. com*/
 *
 * @param keyStorePath a String containing the path to the KeyStore
 * @param keyStorePW   a String containing the KeyStore password
 * @param keyName      a String containing the alias of targeted certificate
 * @param keyPW        a String containing the key password
 * @return the PrivateKeyEntry object containing the targeted private key
 *
 */
public static PrivateKeyEntry getKeyEntry(String keyStorePath, String keyStorePW, String keyName,
        String keyPW) {
    KeyStore ks;
    PrivateKeyEntry keyEntry = null;
    FileInputStream is = null;
    try {
        ks = KeyStore.getInstance("JKS");
        is = new FileInputStream(keyStorePath);
        ks.load(is, keyStorePW.toCharArray());
        keyEntry = (PrivateKeyEntry) ks.getEntry(keyName, new KeyStore.PasswordProtection(keyPW.toCharArray()));
    } catch (FileNotFoundException e) {
        logger.error("FileNotFoundException when attempting to get a key entry in a keystore. " + e);
    } catch (IOException e) {
        logger.error("IOException when attempting to get a key entry in a keystore. " + e);
    } catch (KeyStoreException e) {
        logger.error("KeyStoreException when attempting to get a key entry in a keystore. " + e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException when attempting to get a key entry in a keystore. " + e);
    } catch (CertificateException e) {
        logger.error("CertificateException when attempting to get a key entry in a keystore. " + e);
    } catch (UnrecoverableEntryException e) {
        logger.error("UnrecoverableEntryException when attempting to get a key entry in a keystore. " + e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                logger.error("IOException when attempting to close an input stream. " + ioe);
            }
        }
    }
    return keyEntry;
}

From source file:org.apache.metron.dataservices.auth.AuthToken.java

public static boolean validateToken(final Properties configProps, String authToken) throws Exception {
    KeyStore ks = KeyStore.getInstance("JCEKS");
    String keystoreFile = configProps.getProperty("keystoreFile");
    String keystorePassword = configProps.getProperty("keystorePassword");
    String keystoreAlias = configProps.getProperty("authTokenAlias");
    long tokenMaxAgeInMilliseconds = Long.parseLong(configProps.getProperty("authTokenMaxAge", "600000"));

    FileInputStream fis = null;//from ww w .  j  a v a  2  s. c o m
    try {
        fis = new FileInputStream(keystoreFile);
        ks.load(fis, keystorePassword.toCharArray());
    } finally {
        if (fis != null) {
            fis.close();
        }
    }

    KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(keystorePassword.toCharArray());
    KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry) ks.getEntry(keystoreAlias, protParam);

    SecretKey key = secretKeyEntry.getSecretKey();

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, key);

    byte[] encryptedBytes = Base64.decodeBase64(authToken);

    byte[] unencryptedBytes = cipher.doFinal(encryptedBytes);
    String clearTextToken = new String(unencryptedBytes);

    System.out.println("clearTextToken: " + clearTextToken);
    String[] tokenParts = clearTextToken.split(":");

    if (tokenParts[0].equals("Metron_AuthToken")) {
        long now = System.currentTimeMillis();
        long tokenTime = Long.parseLong(tokenParts[1]);

        if (now > (tokenTime + tokenMaxAgeInMilliseconds)) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }

}

From source file:org.apache.metron.dataservices.auth.AuthToken.java

public static String generateToken(final Properties configProps) throws Exception {

    KeyStore ks = KeyStore.getInstance("JCEKS");
    String keystoreFile = configProps.getProperty("keystoreFile");
    logger.info("keystoreFile: " + keystoreFile);

    String keystorePassword = configProps.getProperty("keystorePassword");
    logger.info("keystorePassword: " + keystorePassword);

    String keystoreAlias = configProps.getProperty("authTokenAlias");
    logger.info("keystoreAlias: " + keystoreAlias);

    FileInputStream fis = null;//from  w ww . ja v a2 s .c o m
    try {
        fis = new FileInputStream(keystoreFile);
        ks.load(fis, keystorePassword.toCharArray());
    } catch (Exception e) {
        logger.error("Error opening keyfile:", e);
        throw e;
    } finally {
        fis.close();
    }

    KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(keystorePassword.toCharArray());
    KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry) ks.getEntry(keystoreAlias, protParam);

    SecretKey key = secretKeyEntry.getSecretKey();

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    String tokenString = "Metron_AuthToken:" + System.currentTimeMillis();

    byte[] encryptedData = cipher.doFinal(tokenString.getBytes());

    String base64Token = new String(Base64.encodeBase64(encryptedData));

    // System.out.println( "base64Token: " + base64Token );

    return base64Token;

}

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

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

    /* Find the keystore. */
    KeyStore keyStore = loadKeyStore(keystoreType, keyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases;
    try {/* ww  w .j  a va 2s .co  m*/
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("could not get aliases", e);
    }
    if (!aliases.hasMoreElements())
        throw new InternalInconsistencyException("keystore is empty");

    try {
        if (!keyStore.isKeyEntry(alias))
            throw new InternalInconsistencyException(String.format("not key entry: %s", alias));
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("key store error", e);
    }

    /* 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:org.jumpmind.security.SecurityService.java

protected SecretKey getSecretKey() throws Exception {
    String password = getKeyStorePassword();
    KeyStore.ProtectionParameter param = new KeyStore.PasswordProtection(password.toCharArray());
    KeyStore ks = getKeyStore(password);
    KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) ks
            .getEntry(SecurityConstants.ALIAS_SYM_SECRET_KEY, param);
    if (entry == null) {
        log.debug("Generating secret key");
        entry = new KeyStore.SecretKeyEntry(getDefaultSecretKey());
        ks.setEntry(SecurityConstants.ALIAS_SYM_SECRET_KEY, entry, param);
        saveKeyStore(ks, password);/* w  w  w. j av a2  s .c  om*/
    } else {
        log.debug("Retrieving secret key");
    }
    return entry.getSecretKey();
}

From source file:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testPKCS1viaPKCS11() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();/* w w  w  .j a v  a 2  s .  c  o  m*/
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true);
    configWriter.println("name=SmartCard");
    configWriter.println("library=/usr/lib/libbeidpkcs11.so.0");
    configWriter.println("slotListIndex=2");

    SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(provider);
    KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
    keyStore.load(null, null);
    PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    RSAPublicKey publicKey = (RSAPublicKey) certificate.getPublicKey();
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(messageBigInteger.toByteArray())));

    // LOG.debug("ASN.1 signature: " + ASN1Dump.dumpAsString(obj)
}

From source file:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testTokenHasBeenRemovedError() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();//  w  w  w  .j  a v  a  2s.  c  om
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true);
    configWriter.println("name=SmartCard");
    configWriter.println("library=/usr/lib/libbeidpkcs11.so.0");
    configWriter.println("slotListIndex=1");

    SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(provider);
    KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
    keyStore.load(null, null);
    {
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKeyEntry.getPrivateKey());
        byte[] toBeSigned = "hello world".getBytes();
        signature.update(toBeSigned);
        byte[] signatureValue = signature.sign();
    }
    JOptionPane.showMessageDialog(null, "Please remove and re-insert the token...");
    {
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKeyEntry.getPrivateKey());
        byte[] toBeSigned = "hello world".getBytes();
        signature.update(toBeSigned);
        byte[] signatureValue = signature.sign();
    }
}

From source file:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testTokenHasBeenRemovedWorkaround() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();/*from   ww  w .  jav  a  2 s.  c  om*/
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true);
    configWriter.println("name=SmartCard");
    configWriter.println("library=/usr/lib/libbeidpkcs11.so.0");
    configWriter.println("slotListIndex=1");

    SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(provider);
    {
        KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
        keyStore.load(null, null);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKeyEntry.getPrivateKey());
        byte[] toBeSigned = "hello world".getBytes();
        signature.update(toBeSigned);
        byte[] signatureValue = signature.sign();

    }
    JOptionPane.showMessageDialog(null, "Please remove and re-insert the token...");
    Security.removeProvider(provider.getName());
    {
        SunPKCS11 provider2 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
        Security.addProvider(provider2);
        KeyStore keyStore = KeyStore.getInstance("PKCS11", provider2);
        keyStore.load(null, null);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKeyEntry.getPrivateKey());
        byte[] toBeSigned = "hello world".getBytes();
        signature.update(toBeSigned);
        byte[] signatureValue = signature.sign();
        Security.removeProvider(provider2.getName());
    }
}