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:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplTest.java

/**
 * @throws java.lang.Exception//from w w  w  .jav  a2 s.c  o m
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    // Just in case, add the BouncyCastle provider
    // It gets added from the CredentialManagerImpl constructor as well
    // but we may need some crypto operations before we invoke the Cred. Manager 
    Security.addProvider(new BouncyCastleProvider());

    // Create a test username and password for a service
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {

        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub

        }
    };
}

From source file:org.wso2.carbon.appfactory.jenkins.AppfactoryPluginManager.java

/**
 * Get auth header//from   w w w  . j  a v a2  s .c  o m
 * @param username username
 * @return Bearer header
 * @throws AppFactoryException
 */
public String getAuthHeader(String username) throws AppFactoryException {
    String keyStoreCredential = getDescriptor().getKeyStorePassword();
    try {
        KeyStore ks = KeyStore.getInstance(JKS);
        ks.load(new FileInputStream(getDescriptor().getKeyStore()), keyStoreCredential.toCharArray());
        PrivateKey key = (PrivateKey) ks.getKey(keyStoreCredential, keyStoreCredential.toCharArray());
        JWSSigner signer = new RSASSASigner((RSAPrivateKey) key);
        JWTClaimsSet claimsSet = new JWTClaimsSet();
        claimsSet.setClaim(AppFactoryConstants.SIGNED_JWT_AUTH_USERNAME, username);
        SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS512), claimsSet);
        signedJWT.sign(signer);

        // generate authorization header value
        return "Bearer " + Base64Utils.encode(signedJWT.serialize().getBytes());
    } catch (Exception e) {
        String msg = "Failed to get primary default certificate";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }
}

From source file:org.signserver.server.cryptotokens.PKCS11CryptoToken.java

@Override
public void importCertificateChain(final List<Certificate> certChain, final String alias,
        final char[] athenticationCode, final Map<String, Object> params, final IServices services)
        throws CryptoTokenOfflineException {
    try {//from   ww  w . ja  v a 2 s  . com
        final KeyStore keyStore = delegate.getActivatedKeyStore();
        final Key key = keyStore.getKey(alias, athenticationCode);

        CryptoTokenHelper.ensureNewPublicKeyMatchesOld(keyStore, alias, certChain.get(0));

        keyStore.setKeyEntry(alias, key, athenticationCode, certChain.toArray(new Certificate[0]));
    } catch (KeyStoreException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (UnrecoverableKeyException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    }
}

From source file:org.ejbca.core.model.ca.catoken.BaseCAToken.java

/**
 * @param keyStore/*from ww  w.j  a va 2s.c  o  m*/
 * @param authCode
 * @throws Exception
 */
protected void setKeys(KeyStore keyStore, String authCode) throws Exception {
    this.mKeys = null;
    final String keyAliases[] = this.keyStrings.getAllStrings();
    final Map<String, KeyPair> mTmp = new Hashtable<String, KeyPair>();
    for (int i = 0; i < keyAliases.length; i++) {
        PrivateKey privateK = (PrivateKey) keyStore.getKey(keyAliases[i],
                (authCode != null && authCode.length() > 0) ? authCode.toCharArray() : null);
        if (privateK == null) {
            log.error(intres.getLocalizedMessage("catoken.noprivate", keyAliases[i]));
            if (log.isDebugEnabled()) {
                for (int j = 0; j < keyAliases.length; j++) {
                    log.debug("Existing alias: " + keyAliases[j]);
                }
            }
        } else {
            PublicKey publicK = readPublicKey(keyStore, keyAliases[i]);
            if (publicK != null) {
                KeyPair keyPair = new KeyPair(publicK, privateK);
                mTmp.put(keyAliases[i], keyPair);
            }
        }
    }
    for (int i = 0; i < keyAliases.length; i++) {
        KeyPair pair = mTmp.get(keyAliases[i]);
        if (log.isDebugEnabled()) {
            log.debug("Testing keys with alias " + keyAliases[i]);
        }
        if (pair == null) {
            log.info("No keys with alias " + keyAliases[i] + " exists.");
        } else {
            testKey(pair); // Test signing for the KeyPair (this could theoretically fail if singing is not allowed by the provider for this key)
            if (log.isDebugEnabled()) {
                log.debug("Key with alias " + keyAliases[i] + " tested.");
            }
        }
    }
    this.mKeys = mTmp;
    if (getCATokenStatus() != ICAToken.STATUS_ACTIVE) {
        throw new Exception("Activation test failed");
    }
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private byte[] generateSignature(String tokenString) {

    byte[] signature = null;

    File ksFile = ConfigurationListener.getLterKeyStore();
    String ksType = ConfigurationListener.getLterKeyStoreType();
    String ksAlias = ConfigurationListener.getLterKeyStoreAlias();
    char[] storePass = ConfigurationListener.getLterStorePasswd().toCharArray();
    char[] keyPass = ConfigurationListener.getLterKeyPasswd().toCharArray();

    try {/*from   w  ww .  j a  v  a 2 s. c  o m*/

        KeyStore ks = KeyStore.getInstance(ksType);
        FileInputStream ksFis = new FileInputStream(ksFile);
        BufferedInputStream ksBufIn = new BufferedInputStream(ksFis);

        ks.load(ksBufIn, storePass);
        PrivateKey priv = (PrivateKey) ks.getKey(ksAlias, keyPass);

        Signature rsa = Signature.getInstance("MD5withRSA");
        rsa.initSign(priv);

        rsa.update(tokenString.getBytes());
        signature = rsa.sign();

    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    return signature;

}

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

static @Nonnull String getToken(@Nonnull String iss, @Nonnull String p12File) throws CloudException {
    if (logger.isDebugEnabled()) {
        logger.debug("iss: " + iss);
        logger.debug("p12File: " + p12File);
    }//from   w  ww. j  a v  a 2  s  . c o  m

    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    StringBuffer token = new StringBuffer();

    try {
        token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

        token.append(".");

        String scope = "https://www.googleapis.com/auth/compute";
        String aud = "https://accounts.google.com/o/oauth2/token";
        String expiry = Long.toString((System.currentTimeMillis() / 1000) + 3600);
        String startTime = Long.toString((System.currentTimeMillis() / 1000));

        String payload = "{\"iss\": \"" + iss + "\", \"scope\": \"" + scope + "\", \"aud\": \"" + aud
                + "\", \"exp\": \"" + expiry + "\", \"iat\": \"" + startTime + "\"}";

        token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

        // TODO: the password is hardcoded. This has to be read from the ctx or from the environment variable
        char[] password = "notasecret".toCharArray();
        FileInputStream iStream = new FileInputStream(new File(p12File));
        KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            store.load(iStream, password);
        } finally {
            try {
                iStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("Could not read the keystore file");
                throw new CloudException(e);
            }
        }
        String alias = "";

        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String keyStoreAlias = aliases.nextElement().toString();
            if (store.isKeyEntry(keyStoreAlias)) {
                alias = keyStoreAlias;
                break;
            }
        }

        PrivateKey privateKey = (PrivateKey) store.getKey(alias, password);

        Signature shaSignature = Signature.getInstance("SHA256withRSA");
        shaSignature.initSign(privateKey);
        shaSignature.update(token.toString().getBytes("UTF-8"));
        String signedToken = Base64.encodeBase64URLSafeString(shaSignature.sign());

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

        //Add the encoded signature
        token.append(signedToken);
        return token.toString();

    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Could not sign the payload with the private key");
        throw new CloudException(e);
    }
}

From source file:org.wso2.carbon.user.core.config.UserStoreConfigXMLProcessor.java

/**
 * Initializes and assign the keyStoreCipher only for the first time.
 *//*  w  w w .  j a va2  s .c  om*/
private void initializeKeyStore() {
    ServerConfigurationService serverConfigurationService = UserStoreMgtDSComponent
            .getServerConfigurationService();

    if (serverConfigurationService == null) {
        String message = "Key store initialization for decrypting secondary store failed due to"
                + " serverConfigurationService is null while attempting to decrypt secondary store";
        log.error(message);
        return;
    }

    if (keyStoreCipher == null) {

        String password = serverConfigurationService.getFirstProperty("Security.KeyStore.Password");
        String keyPass = serverConfigurationService.getFirstProperty("Security.KeyStore.KeyPassword");
        String keyAlias = serverConfigurationService.getFirstProperty("Security.KeyStore.KeyAlias");
        InputStream in = null;
        try {
            KeyStore store = KeyStore
                    .getInstance(serverConfigurationService.getFirstProperty("Security.KeyStore.Type"));
            String file = new File(serverConfigurationService.getFirstProperty("Security.KeyStore.Location"))
                    .getAbsolutePath();
            in = new FileInputStream(file);
            store.load(in, password.toCharArray());
            PrivateKey privateKey = (PrivateKey) store.getKey(keyAlias, keyPass.toCharArray());
            keyStoreCipher = Cipher.getInstance("RSA", "BC");
            keyStoreCipher.init(Cipher.DECRYPT_MODE, privateKey);
        } catch (FileNotFoundException e) {
            String errorMsg = "Keystore File Not Found in configured location";
            log.error(errorMsg, e);
        } catch (IOException e) {
            String errorMsg = "Keystore File IO operation failed";
            log.error(errorMsg, e);
        } catch (InvalidKeyException e) {
            String errorMsg = "Invalid key is used to access keystore";
            log.error(errorMsg, e);
        } catch (KeyStoreException e) {
            String errorMsg = "Faulty keystore";
            log.error(errorMsg, e);
        } catch (GeneralSecurityException e) {
            String errorMsg = "Some parameters assigned to access the " + "keystore is invalid";
            log.error(errorMsg, e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing Registry key store file", e);
                }
            }
        }
    }
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testLocale() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter();
    beIDKeyStoreParameter.setLocale(Locale.FRENCH);
    beIDKeyStoreParameter.setLogger(new TestLogger());
    keyStore.load(beIDKeyStoreParameter);

    PrivateKey privateKey = (PrivateKey) keyStore.getKey("Signature", null);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);/*from  w w w .  j  av  a 2 s . c  o m*/

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    signature.sign();
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

/**
 * Integration test for automatic recovery of a {@link PrivateKey} instance.
 * <p/>/*from w w w .  j av  a2s.co  m*/
 * Automatic recovery should work on the same eID card.
 * <p/>
 * When inserting another eID card however, the automatic recovery should
 * fail.
 * 
 * @throws Exception
 */
@Test
public void testAutoRecovery() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    keyStoreParameter.setAutoRecovery(true);
    keyStoreParameter.setCardReaderStickiness(true);
    keyStore.load(keyStoreParameter);

    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    PublicKey authnPublicKey = keyStore.getCertificate("Authentication").getPublicKey();
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));

    JOptionPane.showMessageDialog(null, "Please remove/insert eID card...");

    signature.initSign(authnPrivateKey);
    signature.update(toBeSigned);
    signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

@Override
public KeyPair getKeyPair(KeyStore ks, String keyAlias, String certAlias, String keyPassword)
        throws CertException {
    KeyPair keyPair = null;//from ww w  .  j a  v  a  2s .  co  m
    try {
        if (!ks.containsAlias(keyAlias)) {
            throw new CertException("Missing keystore key entry for key alias:" + keyAlias);
        }
        if (!ks.containsAlias(certAlias)) {
            throw new CertException("Missing keystore certificate entry for :" + certAlias);
        }
        PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, keyPassword.toCharArray());
        X509Certificate cert = (X509Certificate) ks.getCertificate(certAlias);
        PublicKey publicKey = cert.getPublicKey();
        keyPair = new KeyPair(publicKey, privateKey);
    } catch (UnrecoverableKeyException e) {
        throw new CertException(e);
    } catch (KeyStoreException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    }
    return keyPair;
}