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.digidoc4j.testutils.TestSigningHelper.java

public static byte[] sign(byte[] dataToSign, DigestAlgorithm digestAlgorithm) {
    try {/*ww  w  .  ja va  2s. c o  m*/
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (FileInputStream stream = new FileInputStream("testFiles/signout.p12")) {
            keyStore.load(stream, "test".toCharArray());
        }
        PrivateKey privateKey = (PrivateKey) keyStore.getKey("1", "test".toCharArray());
        final String javaSignatureAlgorithm = "NONEwith" + privateKey.getAlgorithm();

        return AsyncSigning.encrypt(javaSignatureAlgorithm, privateKey,
                addPadding(dataToSign, digestAlgorithm));
    } catch (Exception e) {
        throw new DigiDoc4JException("Loading private key failed");
    }
}

From source file:org.wso2.carbon.identity.user.registration.ui.util.TokenDecrypter.java

private static Element decryptElement(Element encryptedToken) throws Exception {

    ServerConfiguration serverConfig = ServerConfiguration.getInstance();
    PrivateKey key = null;/*from   w w  w . j a va  2 s.  c o m*/
    String keyStoreFile = null;
    String privateKeyPass = null;
    String privateKeyAlias = null;
    String keyStorePass = null;
    String type = null;
    byte[] content = null;

    try {

        keyStoreFile = serverConfig.getFirstProperty("Security.KeyStore.Location");
        keyStorePass = serverConfig.getFirstProperty("Security.KeyStore.Password");
        type = serverConfig.getFirstProperty("Security.KeyStore.Type");
        privateKeyAlias = serverConfig.getFirstProperty("Security.KeyStore.KeyAlias");
        privateKeyPass = serverConfig.getFirstProperty("Security.KeyStore.KeyPassword");
        CryptoUtil.getDefaultCryptoUtil();

        content = readBytesFromFile(keyStoreFile);

        KeyStore keyStore = KeyStore.getInstance(type);
        keyStore.load(new ByteArrayInputStream(content), keyStorePass.toCharArray());

        key = (PrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPass.toCharArray());

        Element kiElem = (Element) encryptedToken.getElementsByTagNameNS(WSConstants.SIG_NS, "KeyInfo").item(0);
        Element encrKeyElem = (Element) kiElem
                .getElementsByTagNameNS(WSConstants.ENC_NS, EncryptionConstants._TAG_ENCRYPTEDKEY).item(0);

        EncryptedKeyProcessor encrKeyProcessor = new EncryptedKeyProcessor();
        encrKeyProcessor.handleEncryptedKey(encrKeyElem, key);

        SecretKey secretKey = WSSecurityUtil.prepareSecretKey(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128,
                encrKeyProcessor.getDecryptedBytes());

        XMLCipher cipher = XMLCipher.getInstance();
        cipher.init(XMLCipher.DECRYPT_MODE, secretKey);

        Document doc = cipher.doFinal(encryptedToken.getOwnerDocument(), encryptedToken);

        return doc.getDocumentElement();
    } catch (Exception e) {
        log.error("error occured while decryptng the token", e);
        throw e;
    }
}

From source file:ee.ria.xroad.common.TestCertUtil.java

/**
 * Loads a private key with the specified org name from a keystore.
 * @param keyStore keystore from which to load the private key
 * @param orgName name of the private key org
 * @param password keystore password/*ww w .  j  a v a 2  s .  c  o m*/
 * @return PrivateKey
 */
public static PrivateKey getKey(KeyStore keyStore, String password, String orgName) {
    try {
        PrivateKey key = (PrivateKey) keyStore.getKey(orgName, password.toCharArray());
        if (key == null) {
            throw new RuntimeException("Unable to get key for " + "name \"" + orgName + "\" using password \""
                    + password + "\" from keystore");
        }

        return key;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Returns the key associated with the given alias, using the given password
 * to recover it.//from   w  w w.  j a  v a  2s .  c o m
 * 
 * @param storePath
 *            the storePath
 * @param password
 *            the password
 * @param alias
 *            the alias name
 * @return the requested key, or null if the given alias does not exist or
 *         does not identify a key-related entry.
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public static PrivateKey getPrivateKey(String storePath, String password, String alias) throws Exception {
    KeyStore store = getKeyStore(new File(storePath).toURL(), password);
    return (PrivateKey) store.getKey(password, password.toCharArray());
}

From source file:ee.sk.hwcrypto.demo.signature.TestSigningData.java

private static byte[] sign(byte[] dataToSign, DigestAlgorithm digestAlgorithm) {
    try {/*from  w  ww. j  a v  a  2 s  .c om*/
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (FileInputStream stream = new FileInputStream(TEST_PKI_CONTAINER)) {
            keyStore.load(stream, TEST_PKI_CONTAINER_PASSWORD.toCharArray());
        }
        PrivateKey privateKey = (PrivateKey) keyStore.getKey("1", TEST_PKI_CONTAINER_PASSWORD.toCharArray());
        final String javaSignatureAlgorithm = "NONEwith" + privateKey.getAlgorithm();

        return encrypt(javaSignatureAlgorithm, privateKey, addPadding(dataToSign, digestAlgorithm));
    } catch (Exception e) {
        throw new DigiDoc4JException("Loading private key failed");
    }
}

From source file:kr.co.exsoft.eframework.util.LicenseUtil.java

/**
 * ??  ?./* w w  w.  j av a  2 s  .  com*/
 * 
 * @param licenseType
 * @param userCount
 * @return String
 */
public static String generateLicenseKey(String licenseType, int userCount) {

    String ksPass = "loveboat";
    String keyPass = "loveboat";
    String alias = "ab942e0f-9e4a-44b9-9f82-0a5f5d48ba12";
    String ret = null;

    try {
        // ??   
        URL url = ClassLoader.getSystemResource("kr/co/exsoft/eframework/cert/exsoft.pfx");
        FileInputStream certfis = new FileInputStream(new File(url.getFile()));

        // Private Key ?.
        BufferedInputStream ksbufin = new BufferedInputStream(certfis);

        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(ksbufin, ksPass.toCharArray());

        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPass.toCharArray());

        // ??  ?.
        ret = spell("EDMsl|" + licenseType + "|" + userCount + "|", key);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return ret;
}

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

public static PrivateKey getPrivateKey(KeyStore keyStore, String alias, String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {

    return (PrivateKey) keyStore.getKey(alias, password.toCharArray());
}

From source file:org.roda.common.certification.OOXMLSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String fileFormat)/*from w ww  .ja va2 s.  c om*/
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
        UnrecoverableKeyException, InvalidFormatException, XMLSignatureException, MarshalException {

    Path output = Files.createTempFile("signed", "." + fileFormat);
    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
    Files.copy(input, output, copyOptions);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(keystore);
    ks.load(is, password.toCharArray());

    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    X509Certificate x509 = (X509Certificate) ks.getCertificate(alias);

    SignatureConfig signatureConfig = new SignatureConfig();
    signatureConfig.setKey(pk);
    signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
    OPCPackage pkg = OPCPackage.open(output.toString(), PackageAccess.READ_WRITE);
    signatureConfig.setOpcPackage(pkg);

    SignatureInfo si = new SignatureInfo();
    si.setSignatureConfig(signatureConfig);
    si.confirmSignature();

    // boolean b = si.verifySignature();
    pkg.close();
    IOUtils.closeQuietly(is);

    return output;
}

From source file:org.bankinterface.util.KeyStoreUtil.java

static PrivateKey getPrivateKey(String url, String alias) {
    Object[] store = signVerifyStore.get(url);
    try {//  ww  w.  jav  a2s .  c  om
        KeyStore ks = (KeyStore) store[0];
        String password = (String) store[1];
        return (PrivateKey) ks.getKey(alias, password.toCharArray());
    } catch (Exception e) {
        logger.error("Get PrivateKey Erorr, URL : " + url + ", Alias :" + alias);
        return null;
    }
}

From source file:prototype.samples.AsyncSigning.java

private static byte[] getExternalSignature(X509Certificate signerCert, DataToSign dataToSign) {
    SignatureToken externalSigner = new ExternalSigner(signerCert) {
        @Override/*  w ww  .j a v  a 2s.com*/
        public byte[] sign(DigestAlgorithm digestAlgorithm, byte[] dataToSign) {
            try {
                KeyStore keyStore = KeyStore.getInstance("PKCS12");
                try (FileInputStream stream = new FileInputStream("testFiles/signout.p12")) {
                    keyStore.load(stream, "test".toCharArray());
                }
                PrivateKey privateKey = (PrivateKey) keyStore.getKey("1", "test".toCharArray());
                final String javaSignatureAlgorithm = "NONEwith" + privateKey.getAlgorithm();

                return encrypt(javaSignatureAlgorithm, privateKey, addPadding(dataToSign));
            } catch (Exception e) {
                throw new DigiDoc4JException("Loading private key failed");
            }
        }

        private byte[] addPadding(byte[] digest) {
            return ArrayUtils.addAll(SHA256.digestInfoPrefix(), digest);
        }

    };

    return externalSigner.sign(dataToSign.getDigestAlgorithm(), dataToSign.getDigestToSign());
}