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:de.brendamour.jpasskit.signing.PKSigningInformationUtil.java

/**
 * Load all signing information necessary for pass generation using two input streams for the key store and the Apple WWDRCA certificate.
 * //from   w ww  .  ja v  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 PKSigningInformation loadSigningInformationFromPKCS12AndIntermediateCertificate(
        final InputStream pkcs12KeyStoreInputStream, final String keyStorePassword,
        final InputStream appleWWDRCAFileInputStream) throws IOException, NoSuchAlgorithmException,
        CertificateException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException {

    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);
    return checkCertsAndReturnSigningInformationObject(signingPrivateKey, signingCert, appleWWDRCACert);
}

From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandaloneTest.java

private void checkClientCert(String clientDn, X509Certificate rootCert) throws Exception {
    String clientDnFile = TlsToolkitStandalone.getClientDnFile(CertificateUtils.reorderDn(clientDn));
    String password;//from  w w w.j  ava  2 s .  c  o m
    try (FileReader fileReader = new FileReader(new File(tempDir, clientDnFile + ".password"))) {
        List<String> lines = IOUtils.readLines(fileReader);
        assertEquals(1, lines.size());
        password = lines.get(0);
    }

    KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString());
    try (FileInputStream fileInputStream = new FileInputStream(new File(tempDir, clientDnFile + ".p12"))) {
        keyStore.load(fileInputStream, password.toCharArray());
    }
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(TlsToolkitStandalone.NIFI_KEY, new char[0]);
    Certificate[] certificateChain = keyStore.getCertificateChain(TlsToolkitStandalone.NIFI_KEY);
    assertEquals(2, certificateChain.length);
    assertEquals(rootCert, certificateChain[1]);
    certificateChain[1].verify(rootCert.getPublicKey());
    certificateChain[0].verify(rootCert.getPublicKey());
    PublicKey publicKey = certificateChain[0].getPublicKey();
    TlsCertificateAuthorityTest.assertPrivateAndPublicKeyMatch(privateKey, publicKey);

}

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

@Test
public void testNonRepudiationSignaturePPDU() throws Exception {

    CCID.riskPPDU(true);/* w ww  . j  a  va 2  s. c o m*/

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(signPrivateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature");
    assertNotNull(signCertificateChain);
}

From source file:org.wso2.carbon.is.migration.util.SecondaryUserstoreCryptoUtil.java

/**
 * Decrypt the given cipher text value using the WSO2 WSAS key.
 * <p>/*from   w ww.  j  av a  2  s.  com*/
 * IMPORTANT: Since this decrypt method is provided to force required transformation, this will not decrypt
 * self-contained ciphertexts. To decrypt self-contained ciphertext use decrypt(byte[] cipherTextBytes)
 *
 * @param cipherTextBytes      The cipher text to be decrypted
 * @param cipherTransformation The transformation that need to decrypt. If it is null, RSA is used as default.
 *                             NOTE: If symmetric encryption enabled, cipherTransformation parameter will be ignored
 * @return Decrypted bytes
 * @throws CryptoException On an error during decryption
 */
public byte[] decrypt(byte[] cipherTextBytes, String cipherTransformation) throws CryptoException {

    byte[] decryptedValue;

    try {
        Cipher keyStoreCipher;
        KeyStore keyStore;
        PrivateKey privateKey;
        KeyStoreManager keyMan = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID,
                ISMigrationServiceDataHolder.getServerConfigurationService(),
                ISMigrationServiceDataHolder.getRegistryService());
        keyStore = keyMan.getPrimaryKeyStore();
        privateKey = (PrivateKey) keyStore.getKey(primaryKeyStoreAlias, primaryKeyStoreKeyPass.toCharArray());
        if (cipherTransformation != null) {
            keyStoreCipher = Cipher.getInstance(cipherTransformation, "BC");
        } else {
            keyStoreCipher = Cipher.getInstance("RSA", "BC");
        }

        keyStoreCipher.init(Cipher.DECRYPT_MODE, privateKey);

        if (cipherTextBytes.length == 0) {
            decryptedValue = "".getBytes();
            if (log.isDebugEnabled()) {
                log.debug("Empty value for plainTextBytes null will persist to DB");
            }
        } else {
            decryptedValue = keyStoreCipher.doFinal(cipherTextBytes);
        }

    } catch (Exception e) {
        throw new CryptoException("errorDuringDecryption", e);
    }
    return decryptedValue;
}

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

@Test
public void testPSS256() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//w w w  .j a  v a  2 s . c  om
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA256withRSAandMGF1");
    signature.initSign(authnPrivateKey);

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

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

From source file:com.microsoft.aad.adal.testapp.MainActivity.java

public void initDeviceCertificateMock() throws NoSuchAlgorithmException, UnrecoverableKeyException,
        CertificateException, KeyStoreException, IOException {
    KeyStore keystore = loadTestCertificate();
    Key key = keystore.getKey(TEST_CERT_ALIAS, PKCS12_PASS.toCharArray());
    RSAPrivateKey privateKey = (RSAPrivateKey) key;
    Certificate cert = keystore.getCertificate(TEST_CERT_ALIAS);
    RSAPublicKey publicKey = (RSAPublicKey) cert.getPublicKey();
    MockDeviceCertProxy.sValidIssuer = true;
    MockDeviceCertProxy.sPrivateKey = privateKey;
    MockDeviceCertProxy.sPublicKey = publicKey;
    MockDeviceCertProxy.sThumbPrint = "test";
    MockDeviceCertProxy.sCertificate = (X509Certificate) cert;
    AuthenticationSettings.INSTANCE.setDeviceCertificateProxyClass(MockDeviceCertProxy.class);
}

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

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

    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);// www .jav  a 2  s. co m

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

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

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

    keyStore.load(null); // reload the keystore.
    authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    signature.initSign(authnPrivateKey);
    signature.update(toBeSigned);
    signature.sign();
}

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

@Test
public void testPSSPrefix() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*w  ww .  j a  v  a 2 s  .c o  m*/
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA1withRSAandMGF1");
    signature.initSign(authnPrivateKey);

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

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

    RSAPublicKey rsaPublicKey = (RSAPublicKey) authnPublicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    String paddedMessage = new String(Hex.encodeHex(messageBigInteger.toByteArray()));
    LOG.debug("padded message: " + paddedMessage);
    assertTrue(paddedMessage.endsWith("bc"));
}

From source file:org.apache.xml.security.test.signature.CreateSignatureTest.java

/**
 * Test for bug 36044 - Canonicalizing an empty node-set throws an 
 * ArrayIndexOutOfBoundsException.//  www.  j  a  va  2 s  . co  m
 */
public void testEmptyNodeSet() throws Exception {

    Document doc = db.newDocument();
    Element envelope = doc.createElementNS("http://www.usps.gov/", "Envelope");
    envelope.appendChild(doc.createTextNode("\n"));
    doc.appendChild(envelope);

    XMLSignature sig = new XMLSignature(doc, null, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    ObjectContainer object1 = new ObjectContainer(doc);
    object1.setId("object-1");
    object1.setMimeType("text/plain");
    sig.appendObject(object1);

    ObjectContainer object2 = new ObjectContainer(doc);

    object2.setId("object-2");
    object2.setMimeType("text/plain");
    object2.setEncoding("http://www.w3.org/2000/09/xmldsig#base64");
    object2.appendChild(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="));
    sig.appendObject(object2);

    Transforms transforms = new Transforms(doc);
    XPathContainer xpathC = new XPathContainer(doc);

    xpathC.setXPath("self::text()");
    transforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElementPlusReturns());
    sig.addDocument("#object-1", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#Object");

    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = null;
    if (BASEDIR != null && !"".equals(BASEDIR)) {
        fis = new FileInputStream(BASEDIR + SEP + "data/org/apache/xml/security/samples/input/keystore.jks");
    } else {
        fis = new FileInputStream("data/org/apache/xml/security/samples/input/keystore.jks");
    }
    ks.load(fis, "xmlsecurity".toCharArray());
    PrivateKey privateKey = (PrivateKey) ks.getKey("test", "xmlsecurity".toCharArray());

    sig.sign(privateKey);
}

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

@Test
public void testSecurityFrameworkBeIDCertificate() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*from ww w  . ja v  a 2s  . c o m*/
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate certificate = (X509Certificate) keyStore.getCertificate("Authentication");
    assertNotNull(privateKey);
    assertNotNull(certificate);

    Service service = ClaimsAwareServiceFactory.getInstance();
    // WS-Addressing via JAX-WS
    IService iservice = service.getWS2007FederationHttpBindingIService(new AddressingFeature());

    BindingProvider bindingProvider = (BindingProvider) iservice;

    AGIVSecurity agivSecurity = new AGIVSecurity(
            "https://auth.beta.agiv.be/ipsts/Services/DaliSecurityTokenServiceConfiguration.svc/CertificateMessage",
            "https://auth.beta.agiv.be/sts/Services/SalvadorSecurityTokenServiceConfiguration.svc/IWSTrust13",
            AGIVSecurity.BETA_REALM, certificate, privateKey);
    agivSecurity.enable(bindingProvider, ClaimsAwareServiceFactory.SERVICE_LOCATION,
            ClaimsAwareServiceFactory.SERVICE_REALM);

    ArrayOfClaimInfo result = iservice.getData(0);

    List<ClaimInfo> claims = result.getClaimInfo();
    for (ClaimInfo claim : claims) {
        LOG.debug(claim.getName() + " = " + claim.getValue());
    }

    agivSecurity.cancelSecureConversationTokens();
}