Example usage for java.security KeyStore getKey

List of usage examples for java.security KeyStore getKey

Introduction

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

Prototype

public final Key getKey(String alias, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Returns the key associated with the given alias, using the given password to recover it.

Usage

From source file:eidassaml.starterkit.Utils.java

/**
 * //from  w  w w .  ja  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:org.roda.common.certification.ODFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String ks, String alias, String password,
        String fileFormat) throws Exception {

    Security.addProvider(new BouncyCastleProvider());
    Path output = Files.createTempFile("odfsigned", "." + fileFormat);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream storeStream = new FileInputStream(ks);
    keystore.load(storeStream, password.toCharArray());
    X509Certificate certificate = (X509Certificate) keystore.getCertificate(keystore.aliases().nextElement());
    Key key = keystore.getKey(alias, password.toCharArray());
    IOUtils.closeQuietly(storeStream);/* ww w  .  j  a  va 2s .co m*/

    ByteArrayInputStream bais = createSignature(input.toString(), certificate, key);
    File file = output.toFile();
    if (file != null) {
        byte[] buffer = new byte[2048];
        int length = 0;
        FileOutputStream fos = new FileOutputStream(file);
        while ((length = bais.read(buffer)) >= 0) {
            fos.write(buffer, 0, length);
        }
        IOUtils.closeQuietly(fos);
    }

    return output;
}

From source file:org.nuxeo.common.codec.Crypto.java

/**
 * Extract secret keys from a keystore looking for {@code keyAlias + algorithm}
 *
 * @param keystorePath Path to the keystore
 * @param keystorePass Keystore password
 * @param keyAlias Key alias prefix. It is suffixed with the algorithm.
 * @param keyPass Key password/*w ww  . j a v  a2 s.  c o m*/
 * @throws GeneralSecurityException
 * @throws IOException
 * @see #IMPLEMENTED_ALGOS
 */
public static Map<String, SecretKey> getKeysFromKeyStore(String keystorePath, char[] keystorePass,
        String keyAlias, char[] keyPass) throws GeneralSecurityException, IOException {
    KeyStore keystore = KeyStore.getInstance("JCEKS");
    try (InputStream keystoreStream = new FileInputStream(keystorePath)) {
        keystore.load(keystoreStream, keystorePass);
    }
    Map<String, SecretKey> secretKeys = new HashMap<>();
    for (String algo : IMPLEMENTED_ALGOS) {
        if (keystore.containsAlias(keyAlias + algo)) {
            SecretKey key = (SecretKey) keystore.getKey(keyAlias + algo, keyPass);
            secretKeys.put(algo, key);
        }
    }
    if (secretKeys.isEmpty()) {
        throw new KeyStoreException(String.format("No alias \"%s<algo>\" found in %s", keyAlias, keystorePath));
    }
    return secretKeys;
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

public static PKSigningInformation loadSigningInformationFromPKCS12FileAndIntermediateCertificateFile(
        final String pkcs12KeyStoreFilePath, final String keyStorePassword, final String appleWWDRCAFilePath)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        NoSuchProviderException, UnrecoverableKeyException {
    addBCProvider();//from   w w  w. ja  v  a 2s.com

    KeyStore pkcs12KeyStore = loadPKCS12File(pkcs12KeyStoreFilePath, keyStorePassword);
    Enumeration<String> aliases = pkcs12KeyStore.aliases();

    PrivateKey signingPrivateKey = null;
    X509Certificate signingCert = null;

    while (aliases.hasMoreElements()) {
        String aliasName = aliases.nextElement();

        Key key = pkcs12KeyStore.getKey(aliasName, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            signingPrivateKey = (PrivateKey) key;
            Object cert = pkcs12KeyStore.getCertificate(aliasName);
            if (cert instanceof X509Certificate) {
                signingCert = (X509Certificate) cert;
                break;
            }
        }
    }

    X509Certificate appleWWDRCACert = loadDERCertificate(appleWWDRCAFilePath);
    if (signingCert == null || signingPrivateKey == null || appleWWDRCACert == null) {
        throw new IOException("Couldn#t load all the neccessary certificates/keys");
    }

    return new PKSigningInformation(signingCert, signingPrivateKey, appleWWDRCACert);
}

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  w  w  w  . java  2 s .  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:de.brendamour.jpasskit.signing.PKSigningUtil.java

/**
 * Load all signing information necessary for pass generation using two input streams for the key store and the Apple WWDRCA certificate.
 * // w  w  w  .  j  av a  2  s.  co  m
 * The caller is responsible for closing the stream after this method returns successfully or fails.
 * 
 * @param pkcs12KeyStoreInputStream
 *            <code>InputStream</code> of the key store
 * @param keyStorePassword
 *            Password used to access the key store
 * @param appleWWDRCAFileInputStream
 *            <code>InputStream</code> of the Apple WWDRCA certificate.
 * @return Signing informatino necessary to sign a pass.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws UnrecoverableKeyException
 */
public static PKSigningInformation loadSigningInformationFromPKCS12AndIntermediateCertificateStreams(
        final InputStream pkcs12KeyStoreInputStream, final String keyStorePassword,
        final InputStream appleWWDRCAFileInputStream) throws IOException, NoSuchAlgorithmException,
        CertificateException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException {
    addBCProvider();

    KeyStore pkcs12KeyStore = loadPKCS12File(pkcs12KeyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases = pkcs12KeyStore.aliases();

    PrivateKey signingPrivateKey = null;
    X509Certificate signingCert = null;

    while (aliases.hasMoreElements()) {
        String aliasName = aliases.nextElement();

        Key key = pkcs12KeyStore.getKey(aliasName, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            signingPrivateKey = (PrivateKey) key;
            Object cert = pkcs12KeyStore.getCertificate(aliasName);
            if (cert instanceof X509Certificate) {
                signingCert = (X509Certificate) cert;
                break;
            }
        }
    }

    X509Certificate appleWWDRCACert = loadDERCertificate(appleWWDRCAFileInputStream);
    if (signingCert == null || signingPrivateKey == null || appleWWDRCACert == null) {
        throw new IOException("Couldn#t load all the neccessary certificates/keys");
    }

    return new PKSigningInformation(signingCert, signingPrivateKey, appleWWDRCACert);
}

From source file:org.panbox.core.pairing.file.PanboxFilePairingUtils.java

public static PanboxFilePairingLoadReturnContainer loadPairingFile(File inputFile, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, IllegalArgumentException {
    ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(inputFile));
    try {/*from   ww  w  .j a va 2 s  .  c o  m*/
        byte[] buffer = new byte[1048576]; //1MB

        ArchiveEntry entry;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;

        // ENTRY 1: devicename
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for device name.");
            throw new IllegalArgumentException("Could not find entry for device name.");
        }

        baos = new ByteArrayOutputStream();
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }

        String devicename = new String(baos.toByteArray());

        // ENTRY 2: eMail
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for eMail.");
            throw new IllegalArgumentException("Could not find entry for eMail.");
        }

        baos = new ByteArrayOutputStream();
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }

        String eMail = new String(baos.toByteArray());

        // ENTRY 3: firstName
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for first name.");
            throw new IllegalArgumentException("Could not find entry for first name.");
        }

        baos = new ByteArrayOutputStream();
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }

        String firstName = new String(baos.toByteArray());

        // ENTRY 4: lastName
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for last name.");
            throw new IllegalArgumentException("Could not find entry for last name.");
        }

        baos = new ByteArrayOutputStream();
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }

        String lastName = new String(baos.toByteArray());

        // ENTRY 5: devKeyStore.p12
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for device key store.");
            throw new IllegalArgumentException("Could not find entry for device key store.");
        }

        KeyStore devKeyStore = KeyStore.getInstance("PKCS12");
        devKeyStore.load(in, password);
        PrivateKey devPKey = (PrivateKey) devKeyStore.getKey(devicename.toLowerCase(), password);
        Certificate[] devCert = devKeyStore.getCertificateChain(devicename.toLowerCase());

        // ENTRY 6: knownDevices.list/knownDevices.bks
        entry = in.getNextEntry(); // knownDevices.list

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for knownDevices.list.");
            throw new IllegalArgumentException("Could not find entry for knownDevices.list.");
        }

        Map<String, X509Certificate> devices = new HashMap<String, X509Certificate>();

        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        Map<String, String> deviceNames = new HashMap<String, String>();

        String line;
        while ((line = br.readLine()) != null) {
            String[] values = line.split(DELIMITER);
            deviceNames.put(values[0], values[1]);
        }

        entry = in.getNextEntry(); // knownDevices.bks

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for knownDevices.bks.");
            throw new IllegalArgumentException("Could not find entry for knownDevices.bks.");
        }

        KeyStore devicesStore = KeyStore.getInstance("BKS");
        devicesStore.load(in, password);

        for (Entry<String, String> device : deviceNames.entrySet()) {
            X509Certificate deviceCert = (X509Certificate) devicesStore.getCertificate(device.getKey());
            devices.put(device.getValue(), deviceCert);
        }

        // ENTRY 7: contacts.vcard
        entry = in.getNextEntry();

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for contacts.");
            throw new IllegalArgumentException("Could not find entry for contacts.");
        }

        File contacts = File.createTempFile("panbox" + (new Random().nextInt(65536) - 32768), null);
        FileOutputStream fos = new FileOutputStream(contacts);
        len = 0;
        while ((len = in.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.flush();
        fos.close();

        // ENTRY 8: ownerKeyStore/ownerCertStore.jks
        entry = in.getNextEntry();

        ByteArrayOutputStream tmp = new ByteArrayOutputStream();
        IOUtils.copy(in, tmp);
        ByteArrayInputStream buf = new ByteArrayInputStream(tmp.toByteArray());

        if (entry == null) {
            logger.error("PanboxClient : loadPairingFile : Could not find entry for owner key store.");
            throw new IllegalArgumentException("Could not find entry for owner key store.");
        }

        KeyStore ownerKeyStore = null;
        try {
            // Check if pairing is MASTER
            ownerKeyStore = KeyStore.getInstance("PKCS12");
            ownerKeyStore.load(buf, password);
            // At this point we know it's a PKCS11 file!
            PrivateKey ownerEncKey = (PrivateKey) ownerKeyStore.getKey("ownerEncKey", password);
            Certificate[] ownerEncCert = ownerKeyStore.getCertificateChain("ownerEncKey");
            PrivateKey ownerSignKey = (PrivateKey) ownerKeyStore.getKey("ownerSignKey", password);
            Certificate[] ownerSignCert = ownerKeyStore.getCertificateChain("ownerSignKey");
            in.close();
            removeInputFile(inputFile);

            return new PanboxFilePairingLoadReturnContainer(eMail, firstName, lastName, password, devicename,
                    devPKey, devCert[0], ownerSignKey, ownerSignCert[0], ownerEncKey, ownerEncCert[0], devices,
                    contacts);
        } catch (Exception e) {
            // SLAVE
            try {
                buf = new ByteArrayInputStream(tmp.toByteArray());
                ownerKeyStore = KeyStore.getInstance("BKS");
                ownerKeyStore.load(buf, password);
                Certificate ownerEncCert = ownerKeyStore.getCertificate("ownerEncCert");
                Certificate ownerSignCert = ownerKeyStore.getCertificate("ownerSignCert");
                in.close();
                removeInputFile(inputFile);

                return new PanboxFilePairingLoadReturnContainer(eMail, firstName, lastName, password,
                        devicename, devPKey, devCert[0], null, ownerSignCert, null, ownerEncCert, devices,
                        contacts);
            } catch (Exception ex) {
                logger.error(
                        "PanboxClient : loadPairingFile : Could not determine if pairing file was master or slave.");
                throw new IllegalArgumentException("Pairing type was unknown. Broken file?");
            }
        }
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
            | UnrecoverableKeyException | IllegalArgumentException e) {
        in.close();
        throw e;
    }

}

From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String ks, String alias, String password,
        String fileFormat) throws IOException, GeneralSecurityException, DocumentException {

    Security.addProvider(new BouncyCastleProvider());
    Path output = Files.createTempFile("odfsigned", "." + fileFormat);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream storeStream = new FileInputStream(ks)) {
        keystore.load(storeStream, password.toCharArray());

        X509Certificate certificate = (X509Certificate) keystore
                .getCertificate(keystore.aliases().nextElement());
        Key key = keystore.getKey(alias, password.toCharArray());

        try (ByteArrayInputStream bais = createSignature(input.toString(), certificate, key)) {
            File file = output.toFile();
            if (file != null && bais != null) {
                byte[] buffer = new byte[2048];
                int length = 0;
                try (FileOutputStream fos = new FileOutputStream(file)) {
                    while ((length = bais.read(buffer)) >= 0) {
                        fos.write(buffer, 0, length);
                    }/*from w w w .  ja  v a  2  s  .  c  om*/
                }
            }
        }
    }

    return output;
}

From source file:com.gamesalutes.utils.EncryptUtils.java

private static PrivateKey readKeyStoreKey(InputStream in, String storeType, String alias, char[] pass)
        throws Exception {
    try {/*from   w w w  .  j a  va 2  s .  c  o m*/
        KeyStore ks = KeyStore.getInstance(storeType);
        //load the key store
        //TODO: specify other than "null" if want key store integrity check
        //need key store passwd
        ks.load(in, null);
        return (PrivateKey) ks.getKey(alias, pass);
    } finally {
        MiscUtils.closeStream(in);
    }
}

From source file:org.dasein.cloud.google.GenerateToken.java

public static String getToken(String iss, String p12File) {

    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    String claimTemplate = "'{'\"iss\": \"{0}\", \"scope\": \"{1}\", \"aud\": \"{2}\", \"exp\": \"{3}\", \"iat\": \"{4}\"'}'";

    try {// www.  j a v  a 2  s  .c  o m
        StringBuffer token = new StringBuffer();

        //Encode the JWT Header and add it to our string to sign
        token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

        //Separate with a period
        token.append(".");

        //Create the JWT Claims Object
        String[] claimArray = new String[5];
        claimArray[0] = iss;
        claimArray[1] = "https://www.googleapis.com/auth/compute";
        claimArray[2] = "https://accounts.google.com/o/oauth2/token";
        claimArray[3] = Long.toString((System.currentTimeMillis() / 1000) + 300);
        claimArray[4] = Long.toString((System.currentTimeMillis() / 1000));
        MessageFormat claims;
        claims = new MessageFormat(claimTemplate);
        String payload = claims.format(claimArray);
        //         System.out.println(claimArray[3]);
        //         System.out.println(claimArray[4]);
        //Add the encoded claims object
        token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

        char[] password = "notasecret".toCharArray();
        FileInputStream fin = new FileInputStream(new File(p12File));
        KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            store.load(fin, password);
        } finally {
            try {
                fin.close();
            } catch (IOException e) {
            }
        }
        String alias = "";
        // KeyStore keystore = getKeyStore(password);            
        Enumeration<String> enum1 = store.aliases(); // List the aliases
        while (enum1.hasMoreElements()) {
            String keyStoreAlias = enum1.nextElement().toString();
            if (store.isKeyEntry(keyStoreAlias)) { //Does alias refer to a private key?
                alias = keyStoreAlias;
                break;
            }
        }
        PrivateKey privateKey = (PrivateKey) store.getKey(alias, password);

        //Sign the JWT Header + "." + JWT Claims Object
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(token.toString().getBytes("UTF-8"));
        String signedPayload = Base64.encodeBase64URLSafeString(signature.sign());

        //Separate with a period
        token.append(".");

        //Add the encoded signature
        token.append(signedPayload);

        //      System.out.println(token.toString());
        return token.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}