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.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Creates a SOAP message with a signature.
 * <p>//from w ww.ja v  a 2 s . c o  m
 * A valid SOAP message is required, this will be the message to be signed.
 * 
 * @param pathBase
 *            path to the SOAP message to sign
 * @param privateKeyAlias
 *            alias for the private key
 * @param privateKeyPass
 *            password for the private key
 * @param certificateAlias
 *            alias for the certificate
 * @param keystore
 *            key store for the signing
 * @return a singed SOAP message
 * @throws Exception
 *             if any error occurs during the message creation
 */
public static final SOAPMessage getSignedMessage(final String pathBase, final String privateKeyAlias,
        final String privateKeyPass, final String certificateAlias, final KeyStore keystore) throws Exception {
    Element root = null;
    String BaseURI = new ClassPathResource(pathBase).getURI().toString();
    SOAPMessage soapMessage;
    Base64Converter base64 = new Base64Converter();
    String token;
    Node binaryToken;
    X509Certificate cert;
    PrivateKey privateKey;
    XMLSignature sig;

    soapMessage = getMessageToSign(pathBase);

    // get the private key used to sign, from the keystore
    privateKey = (PrivateKey) keystore.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    cert = (X509Certificate) keystore.getCertificate(certificateAlias);

    // create basic structure of signature
    Document doc = toDocument(soapMessage);

    org.apache.xml.security.Init.init();

    sig = getSignature(doc, BaseURI, cert, privateKey);

    // optional, but better
    root = doc.getDocumentElement();
    root.normalize();
    root.getElementsByTagName("wsse:Security").item(0).appendChild(sig.getElement());

    token = base64.encode(cert.getEncoded());

    binaryToken = root.getElementsByTagName("wsse:BinarySecurityToken").item(0);
    binaryToken.setTextContent(token);

    // write signature to file
    XMLUtils.outputDOMc14nWithComments(doc, System.out);

    return toMessage(doc);
}

From source file:com.bernardomg.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Creates a SOAP message with a signature.
 * <p>/*from   ww  w  .  ja  va  2 s .co  m*/
 * A valid SOAP message is required, this will be the message to be signed.
 * 
 * @param pathBase
 *            path to the SOAP message to sign
 * @param privateKeyAlias
 *            alias for the private key
 * @param privateKeyPass
 *            password for the private key
 * @param certificateAlias
 *            alias for the certificate
 * @param keystore
 *            key store for the signing
 * @return a singed SOAP message
 * @throws Exception
 *             if any error occurs during the message creation
 */
public static final SOAPMessage getSignedMessage(final String pathBase, final String privateKeyAlias,
        final String privateKeyPass, final String certificateAlias, final KeyStore keystore) throws Exception {
    Element root = null;
    final String BaseURI = new ClassPathResource(pathBase).getURI().toString();
    SOAPMessage soapMessage;
    final Base64Converter base64 = new Base64Converter();
    String token;
    Node binaryToken;
    X509Certificate cert;
    PrivateKey privateKey;
    XMLSignature sig;

    soapMessage = getMessageToSign(pathBase);

    // get the private key used to sign, from the keystore
    privateKey = (PrivateKey) keystore.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    cert = (X509Certificate) keystore.getCertificate(certificateAlias);

    // create basic structure of signature
    final Document doc = toDocument(soapMessage);

    org.apache.xml.security.Init.init();

    sig = getSignature(doc, BaseURI, cert, privateKey);

    // optional, but better
    root = doc.getDocumentElement();
    root.normalize();
    root.getElementsByTagName("wsse:Security").item(0).appendChild(sig.getElement());

    token = base64.encode(cert.getEncoded());

    binaryToken = root.getElementsByTagName("wsse:BinarySecurityToken").item(0);
    binaryToken.setTextContent(token);

    // write signature to file
    XMLUtils.outputDOMc14nWithComments(doc, System.out);

    return toMessage(doc);
}

From source file:org.wso2.carbon.identity.sso.saml.TestUtils.java

public static void prepareCredentials(X509Credential x509Credential)
        throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {

    KeyStore keyStore = TestUtils.loadKeyStoreFromFileSystem(
            TestUtils.getFilePath(TestConstants.KEY_STORE_NAME), TestConstants.WSO2_CARBON, "JKS");
    X509Certificate[] issuerCerts = null;
    Certificate[] certificates;/*from w  ww .java2 s  . c o  m*/

    certificates = keyStore.getCertificateChain(TestConstants.WSO2_CARBON);
    issuerCerts = new X509Certificate[certificates.length];

    int i = 0;
    for (Certificate certificate : certificates) {
        issuerCerts[i++] = (X509Certificate) certificate;
    }
    when(x509Credential.getEntityCertificate()).thenReturn((X509Certificate) certificates[0]);
    when(x509Credential.getEntityCertificateChain()).thenReturn(Arrays.asList(issuerCerts));
    when(x509Credential.getPrivateKey()).thenReturn(
            (PrivateKey) keyStore.getKey(TestConstants.WSO2_CARBON, TestConstants.WSO2_CARBON.toCharArray()));
    when(x509Credential.getPublicKey()).thenReturn(issuerCerts[0].getPublicKey());
}

From source file:org.gridgain.grid.tools.license.GridLicenseGeneratorV1.java

/**
 * Load private key from key store.//w w w  .  ja  va2 s .com
 *
 * @return Private key.
 * @throws GridException If key loading failed.
 */
private static PrivateKey getKey() throws GridException {
    KeyStore ks;

    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (Exception e) {
        throw new GridException("Failed to get key store instance.", e);
    }

    File ksFile = new File(U.getGridGainHome() + FS + "keystore", KEY_STORE);

    if (!ksFile.exists() || !ksFile.canRead())
        throw new GridException("Key store file doesn't exist or is not readable: " + ksFile.getAbsolutePath());

    InputStream in;

    try {
        in = new FileInputStream(ksFile);
    } catch (IOException e) {
        throw new GridException("Failed to open key store file: " + ksFile.getAbsolutePath(), e);
    }

    try {
        ks.load(in, KEY_STORE_PWD.toCharArray());

        return (PrivateKey) ks.getKey(KEY_ALIAS, KEY_STORE_PWD.toCharArray());
    } catch (Exception e) {
        throw new GridException("Failed to get private key from key store [keystore=" + KEY_STORE + ", alias="
                + KEY_ALIAS + ']', e);
    } finally {
        U.close(in, null);
    }
}

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

final public static _CRYPTOfactory getInstanceFromKeystore(final KeyStore keystore, final char[] keystorepass,
        final String alias)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        FileNotFoundException, IOException, IllegalArgumentException, SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
    final Key keyFromStore = keystore.getKey(alias, keystorepass);
    final String type = keyFromStore.getAlgorithm();
    return new _CRYPTOfactory(
            (Crypter) Class.forName(_CRYPTOfactory.class.getPackage().getName() + "." + type + "Crypter")
                    .getConstructor(byte[].class).newInstance(keyFromStore.getEncoded()));
}

From source file:org.structr.util.StructrLicenseManager.java

private static void sign(final Map<String, String> properties, final String keystoreFileName,
        final String password) {

    final String src = collectLicenseFieldsForSignature(properties);

    try {// www  .j  av a  2  s.c  o  m

        final byte[] data = src.getBytes(CharSet);
        final Signature signer = Signature.getInstance(SignatureAlgorithm);
        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        try (final InputStream is = new FileInputStream(keystoreFileName)) {

            keyStore.load(is, password.toCharArray());

            final Key key = keyStore.getKey(KeystoreAlias, password.toCharArray());

            signer.initSign((PrivateKey) key);
            signer.update(data);

            properties.put(SignatureKey, Hex.encodeHexString(signer.sign()));
        }

    } catch (Throwable t) {
        logger.warn("Unable to sign license.", t);
    }
}

From source file:com.indivica.olis.Driver.java

public static String signData2(String data) {
    X509Certificate cert = null;//www.  ja va2s  .  c  o m
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = OscarProperties.getInstance().getProperty("olis_ssl_keystore_password", "changeit");
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

        keystore = KeyStore.getInstance("JKS");
        // Load the keystore
        keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")),
                pwd.toCharArray());

        //Enumeration e = keystore.aliases();
        String name = "olis";

        // Get the private key and the certificate
        priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray());

        FileInputStream is = new FileInputStream(
                OscarProperties.getInstance().getProperty("olis_returned_cert"));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(is);

        // I'm not sure if this is necessary

        ArrayList<Certificate> certList = new ArrayList<Certificate>();
        certList.add(cert);

        Store certs = new JcaCertStore(certList);

        // Encrypt data
        CMSSignedDataGenerator sgen = new CMSSignedDataGenerator();

        // What digest algorithm i must use? SHA1? MD5? RSA?...
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv);
        sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));

        // I'm not sure this is necessary
        sgen.addCertificates(certs);

        // I think that the 2nd parameter need to be false (detached form)
        CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true);

        byte[] signedData = csd.getEncoded();
        byte[] signedDataB64 = Base64.encode(signedData);

        result = new String(signedDataB64);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e);
    }
    return result;
}

From source file:nu.yona.server.AppServiceApplication.java

@Bean
@Qualifier("appleMobileConfigSignerKey")
public PrivateKey appleMobileConfigSignerKey(KeyStore keyStore) {
    try {/*  w w w .  jav a2 s . c o m*/
        return (PrivateKey) keyStore.getKey(yonaProperties.getAppleMobileConfig().getSigningAlias(),
                yonaProperties.getAppleMobileConfig().getSigningKeyStorePassword().toCharArray());
    } catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e) {
        throw YonaException.unexpected(e);
    }
}

From source file:org.chaston.oakfunds.xsrf.XsrfSigner.java

private PrivateKey loadPrivateKey() throws IOException, GeneralSecurityException {
    InputStream keyStream = getClass().getClassLoader().getResourceAsStream("META-INF/secrets/xsrf.p12");
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(keyStream, "ofxsrf".toCharArray());
    return (PrivateKey) ks.getKey("xsrf", "ofxsrf".toCharArray());
}

From source file:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfig.java

@Override
public PrivateKey getPrivateKey() {
    if (p12KeyFile != null) {
        try {/*from ww w.j a  v  a 2 s.c om*/
            KeyStore p12KeyStore = getP12KeyStore();
            return (PrivateKey) p12KeyStore.getKey(DEFAULT_P12_ALIAS, DEFAULT_P12_SECRET.toCharArray());
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to read private key", e);
        } catch (GeneralSecurityException e) {
            LOGGER.log(Level.SEVERE, "Failed to read private key", e);
        }
    }
    return null;
}