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:com.zacwolf.commons.crypto.Crypter_AES.java

/**
 * @param keyStore//from  w  w w  .j a v a2 s  .  c  o m
 * @param keystorepass
 * @param alias
 * @param cipher
 * @param salter
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 */
public Crypter_AES(final KeyStore keyStore, final char[] keystorepass, final String alias, final String cipher,
        final SecureRandom salter)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    this(keyStore.getKey(alias, keystorepass).getEncoded(), cipher, salter);
}

From source file:org.gameontext.map.auth.PlayerClient.java

/**
 * Obtain the key we'll use to sign the jwts we use to talk to Player endpoints.
 *
 * @throws IOException/* w  w  w .j a  v a  2  s. co m*/
 *             if there are any issues with the keystore processing.
 */
private synchronized void getKeyStoreInfo() {
    try {
        // load up the keystore..
        FileInputStream is = new FileInputStream(keyStore);
        KeyStore signingKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
        signingKeystore.load(is, keyStorePW.toCharArray());

        // grab the key we'll use to sign
        signingKey = signingKeystore.getKey(keyStoreAlias, keyStorePW.toCharArray());

    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException
            | IOException e) {
        throw new IllegalStateException("Unable to get required keystore: " + keyStore, e);
    }
}

From source file:com.google.identitytoolkit.RpcHelper.java

private RsaSHA256Signer initRsaSHA256Signer(String serviceAccountEmail, InputStream keyStream) {
    try {//from  w  w  w .  ja  v a 2 s.  c  om
        if (serviceAccountEmail != null && keyStream != null) {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(keyStream, "notasecret".toCharArray());
            return new RsaSHA256Signer(serviceAccountEmail, null,
                    (RSAPrivateKey) keyStore.getKey("privatekey", "notasecret".toCharArray()));
        }
    } catch (KeyStoreException e) {
        log.warning("can not initialize service account signer: " + e);
    } catch (CertificateException e) {
        log.warning("can not initialize service account signer: " + e);
    } catch (UnrecoverableKeyException e) {
        log.warning("can not initialize service account signer: " + e);
    } catch (NoSuchAlgorithmException e) {
        log.warning("can not initialize service account signer: " + e);
    } catch (IOException e) {
        log.warning("can not initialize service account signer: " + e);
    } catch (InvalidKeyException e) {
        log.warning("can not initialize service account signer: " + e);
    }
    log.warning("service account is set to null due to: email = " + serviceAccountEmail + "keystream = "
            + keyStream);
    return null;
}

From source file:com.zacwolf.commons.crypto.Crypter_Blowfish.java

/**
 * @param keyStore//w w  w  . j av a 2s .  c  o m
 * @param keystorepass
 * @param alias
 * @param cipher
 * @param salter
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 */
public Crypter_Blowfish(final KeyStore keyStore, final String keystorepass, final String alias,
        final String cipher, final SecureRandom salter)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    this(keyStore.getKey(alias, keystorepass.toCharArray()).getEncoded(), cipher, salter);
}

From source file:com.zacwolf.commons.crypto.Crypter_Blowfish.java

/**
 * @param keyStore//www.  j  a va  2  s. c om
 * @param keystorepass
 * @param alias
 * @param cipher
 * @param salter
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 */
public Crypter_Blowfish(final KeyStore keyStore, final char[] keystorepass, final String alias,
        final String cipher, final SecureRandom salter)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    this(keyStore.getKey(alias, keystorepass).getEncoded(), cipher, salter);
}

From source file:org.openanzo.security.keystore.SecretKeyStore.java

/**
 * Loads the secret key to use for encryption and decryption. It will read the key from the keystore if it exists. Otherwise it will create a new randomly
 * generated key and save it in a keystore at the given file. It will use the algorithm defined in the <code>algorithm</code> member.
 * /* w ww  .  j a  v a2 s .  c  om*/
 * @param keyStoreStream
 *            stream from which to read the keystore which holds the secret key. If null, a new keystore is created.
 * @param password
 *            password used to protect the and integrity-check the secret key.
 * @param keyStoreDestination
 *            File path to which to save the keystore in case it is newly created or a new key was added. If null, then nothing is written out.
 * @return the loaded or newly generated secret key.
 * @throws AnzoException
 */
private SecretKey loadKey(InputStream keyStoreStream, String password, File keyStoreDestination,
        String keystoreType) throws AnzoException {

    try {
        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(keyStoreStream, password.toCharArray());

        Key key = null;
        if (keyStore.containsAlias(KEY_NAME)) {
            key = keyStore.getKey(KEY_NAME, password.toCharArray());
        } else {
            log.warn("Could not find key '{}' within keystore. Generating a new key.", KEY_NAME);
            KeyGenerator kgen = KeyGenerator.getInstance(algorithm);
            key = kgen.generateKey();
            keyStore.setKeyEntry(KEY_NAME, key, password.toCharArray(), new Certificate[0]);
            if (keyStoreDestination != null) {
                log.warn("Storing new key in the keystore.");
                OutputStream outputStream = null;
                try {
                    outputStream = FileUtils.openOutputStream(keyStoreDestination);
                    keyStore.store(outputStream, password.toCharArray());
                } finally {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                }

            }
        }

        if (!(key instanceof SecretKey))
            throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR,
                    "key must be of type SecretKey: " + key);
        return (SecretKey) key;
    } catch (GeneralSecurityException e) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e);
    } catch (IOException e) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e);
    }

}

From source file:test.integ.be.e_contract.mycarenet.tarification.TarificationClientTest.java

@Test
public void testTarificationConsultation() throws Exception {
    // STS//from   w  ww .j  av  a 2 s  .  co  m
    EHealthSTSClient client = new EHealthSTSClient(
            "https://services-acpt.ehealth.fgov.be/IAM/Saml11TokenService/Legacy/v1");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter();
    beIDKeyStoreParameter.addPPDUName("digipass 870");
    beIDKeyStoreParameter.addPPDUName("digipass 875");
    beIDKeyStoreParameter.addPPDUName("digipass 920");
    keyStore.load(beIDKeyStoreParameter);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // Tarification
    TarificationClient tarificationClient = new TarificationClient(
            "https://services-acpt.ehealth.fgov.be/MyCareNet/Tarification/v1");
    tarificationClient.setCredentials(eHealthPrivateKey, assertionString);

    ObjectFactory objectFactory = new ObjectFactory();
    SendRequestType sendRequest = objectFactory.createSendRequestType();

    DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
    GregorianCalendar issueInstantCal = new GregorianCalendar();
    DateTime issueInstantDateTime = new DateTime();
    issueInstantCal.setTime(issueInstantDateTime.toDate());
    XMLGregorianCalendar issueInstant = datatypeFactory.newXMLGregorianCalendar(issueInstantCal);
    sendRequest.setIssueInstant(issueInstant);

    // TODO...

    tarificationClient.tarificationConsultation(sendRequest);

}

From source file:test.integ.be.agiv.security.PKCS12Test.java

@Test
public void testLoadPKCS12() throws Exception {
    Config config = new Config();
    String pkcs12Path = config.getPKCS12Path();
    String pkcs12Password = config.getPKCS12Password();

    InputStream pkcs12InputStream = new FileInputStream(pkcs12Path);
    assertNotNull(pkcs12InputStream);

    LOG.debug("loading PKCS12 keystore");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(pkcs12InputStream, pkcs12Password.toCharArray());

    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
        LOG.debug("certificate: " + certificate);
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, pkcs12Password.toCharArray());
        LOG.debug("private key algo: " + privateKey.getAlgorithm());
        assertEquals("RSA", privateKey.getAlgorithm());
        LOG.debug("certificate fingerprint: " + DigestUtils.shaHex(certificate.getEncoded()));
    }/*from ww w. j  a  v  a2  s  .  co  m*/
}

From source file:mitm.BouncyCastleSslEngineSource.java

public void initializeServerCertificates(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames)
        throws GeneralSecurityException, OperatorCreationException, IOException {

    KeyStore ks = CertificateHelper.createServerCertificate(commonName, subjectAlternativeNames, authority,
            caCert, caPrivKey);/*from  w  w  w .  ja  v  a 2 s.co m*/

    PrivateKey key = (PrivateKey) ks.getKey(authority.alias(), authority.password());
    exportPem(authority.aliasFile("-" + commonName + "-key.pem"), key);

    Object[] certs = ks.getCertificateChain(authority.alias());
    exportPem(authority.aliasFile("-" + commonName + "-cert.pem"), certs);
}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public void initialize(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    onSharedPreferenceChanged(settings, null);

    settings.registerOnSharedPreferenceChangeListener(this);

    try {//  w  w  w.j av  a  2s .  co m
        KeyStore keystoreCA = KeyStore.getInstance(KEYSTORE_TYPE);
        keystoreCA.load(context.getResources().openRawResource(R.raw.keystore), PWD);

        KeyStore keystoreClient = null;

        File file = context.getFileStreamPath(KEYSTORE_CLIENT_FILENAME);

        if (file.exists()) {
            keystoreClient = KeyStore.getInstance(KEYSTORE_TYPE);
            InputStream in = new FileInputStream(file);
            keystoreClient.load(in, PWD);
        }

        ready = keystoreClient != null && keystoreClient.getKey(MDM_CLIENT_CERT_ALIAS, PWD) != null;

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystoreCA);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(keystoreClient, PWD);

        sslContext = SSLContext.getInstance("TLS");

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    } catch (Exception e) {
        LogManager.debug(MDMManager.class.getSimpleName(), "load keystore error", e);
    }
}