Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

In this page you can find the example usage for java.security KeyStore getCertificate.

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:org.apache.james.jmap.crypto.JamesSignatureHandler.java

@Override
public void init() throws Exception {
    KeyStore keystore = KeyStore.getInstance(JKS);
    InputStream fis = fileSystem.getResource(jmapConfiguration.getKeystore());
    keystore.load(fis, jmapConfiguration.getSecret().toCharArray());
    publicKey = keystore.getCertificate(ALIAS).getPublicKey();
    Key key = keystore.getKey(ALIAS, jmapConfiguration.getSecret().toCharArray());
    if (!(key instanceof PrivateKey)) {
        throw new Exception("Provided key is not a PrivateKey");
    }//from w  w  w  .  ja v a 2  s  .  co  m
    privateKey = (PrivateKey) key;
}

From source file:org.apache.syncope.core.jwt.STSJWTSSOProvider.java

public STSJWTSSOProvider() throws Exception {
    // Load verification cert
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("sts_ver.jks", this.getClass()),
            "stsspass".toCharArray());
    X509Certificate cert = (X509Certificate) keyStore.getCertificate("mykey");

    delegate = new PublicKeyJwsSignatureVerifier(cert, SignatureAlgorithm.RS256);
}

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

private void checkXmlSignatureSoftwareStack(boolean cert) throws Exception {
    Init.init();/*w w  w.j a v  a 2 s.c  o m*/
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document testDocument = documentBuilder.newDocument();

    Element rootElement = testDocument.createElementNS("urn:namespace", "tns:document");
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:namespace");
    testDocument.appendChild(rootElement);
    Element childElement = testDocument.createElementNS("urn:childnamespace", "t:child");
    childElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:t", "urn:childnamespace");
    childElement.appendChild(testDocument.createTextNode("hello world"));
    rootElement.appendChild(childElement);

    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    X509Certificate signingCert = null;
    if (cert) {
        // get key & self-signed certificate from keystore
        String fs = System.getProperty("file.separator");
        FileInputStream fis = new FileInputStream(BASEDIR + fs + "data" + fs + "test.jks");
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(fis, "changeit".toCharArray());
        signingCert = (X509Certificate) ks.getCertificate("mullan");
        publicKey = signingCert.getPublicKey();
        privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray());
    } else {
        KeyPair keyPair = KeyPairGenerator.getInstance("DSA").generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();
    }

    XMLSignature signature = new XMLSignature(testDocument, "", XMLSignature.ALGO_ID_SIGNATURE_DSA,
            Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);

    Element signatureElement = signature.getElement();
    rootElement.appendChild(signatureElement);

    Transforms transforms = new Transforms(testDocument);
    XPathContainer xpath = new XPathContainer(testDocument);
    xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
    xpath.setXPath("not(ancestor-or-self::ds:Signature)");
    transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns());
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    signature.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1);

    if (cert) {
        signature.addKeyInfo(signingCert);
    } else {
        signature.addKeyInfo(publicKey);
    }

    Element nsElement = testDocument.createElementNS(null, "nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);

    signature.sign(privateKey);

    // TransformerFactory tf = TransformerFactory.newInstance();
    // Transformer t = tf.newTransformer();
    // t.transform(new DOMSource(testDocument), new StreamResult(System.out));

    NodeList signatureElems = XPathAPI.selectNodeList(testDocument, "//ds:Signature", nsElement);
    signatureElement = (Element) signatureElems.item(0);
    XMLSignature signatureToVerify = new XMLSignature(signatureElement, "");

    boolean signResult = signatureToVerify.checkSignatureValue(publicKey);

    assertTrue(signResult);
}

From source file:org.lockss.util.TestKeyStoreUtil.java

public void testCreateSharedPLNKeyStores() throws Exception {
    List<String> hosts = ListUtil.list("host1", "host2.foo.bar", "host3");
    List<String> hosts2 = ListUtil.list("host3", "host4");
    File dir = getTempDir();/*from w w w .j  av a2 s  .  c o m*/
    File pub = new File(dir, "pub.ks");
    KeyStoreUtil.createSharedPLNKeyStores(dir, hosts, pub, "pubpass", MiscTestUtil.getSecureRandom());
    assertPubKs(pub, "pubpass", hosts);
    for (String host : hosts) {
        assertPrivateKs(new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")),
                host);
    }
    KeyStore pubks1 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass");

    Certificate host1cert1 = pubks1.getCertificate("host1.crt");
    Certificate host3cert1 = pubks1.getCertificate("host3.crt");

    String host1priv1 = StringUtil.fromFile(new File(dir, "host1.jceks"));
    String host3priv1 = StringUtil.fromFile(new File(dir, "host3.jceks"));

    // Now add host4 and generate a new key for host3
    KeyStoreUtil.createSharedPLNKeyStores(dir, hosts2, pub, "pubpass", MiscTestUtil.getSecureRandom());
    List<String> both = ListUtils.sum(hosts, hosts2);
    assertPubKs(pub, "pubpass", both);
    for (String host : both) {
        assertPrivateKs(new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")),
                host);
    }
    KeyStore pubks2 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass");
    // host1 should have the same cert, host3 not
    Certificate host1cert2 = pubks2.getCertificate("host1.crt");
    Certificate host3cert2 = pubks2.getCertificate("host3.crt");
    assertEquals(host1cert1, host1cert2);
    assertNotEquals(host3cert1, host3cert2);

    // host1's private key file should be the same, host3's not
    String host1priv2 = StringUtil.fromFile(new File(dir, "host1.jceks"));
    String host3priv2 = StringUtil.fromFile(new File(dir, "host3.jceks"));
    assertEquals(host1priv1, host1priv2);
    assertNotEquals(host3priv1, host3priv2);
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testWriteAuthCertToFile() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*  w w  w .j  av  a 2 s .c  o  m*/
    Certificate authnCert = keyStore.getCertificate("Authentication");
    LOG.debug("authn cert: " + authnCert);
    File tmpFile = File.createTempFile("eid-authn-cert-", ".der");
    FileUtils.writeByteArrayToFile(tmpFile, authnCert.getEncoded());
    LOG.debug("tmp authn cert file: " + tmpFile.getAbsolutePath());
}

From source file:test.integ.be.e_contract.mycarenet.async.AsyncClientTest.java

@Test
public void testEcho() throws Exception {
    // setup/*from  w w w .  ja  v a 2  s.c o m*/
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    try {
        // setup
        Config config = new Config();
        PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey();
        LOG.debug("package license key username: " + packageLicenseKey.getUsername());
        LOG.debug("package license key password: " + packageLicenseKey.getPassword());
        AsyncClient asyncClient = new AsyncClient("https://pilot.mycarenet.be/mycarenet-ws/care-provider/async",
                sessionKey, packageLicenseKey);
        String message = "hello world";

        // operate
        String result;
        try {
            result = asyncClient.echo(message);
        } finally {
            LOG.debug("payload: " + asyncClient.getPayload());
        }

        // verify
        assertEquals(result, message);
    } finally {
        // operate
        xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate);

        // verify
        assertFalse(sessionKey.isValid());
    }
}

From source file:test.unit.be.fedict.hsm.entity.KeyStoreSingletonBeanTest.java

@Test
public void testSignature() throws Exception {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test");
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();/*ww  w .  ja v  a  2s  .  c om*/

    KeyStoreEntity keyStoreEntity = new KeyStoreEntity("test", KeyStoreType.PKCS12,
            KeyStoreSingletonBeanTest.class.getResource("/keystore.p12").toURI().getPath(), "secret");
    entityManager.persist(keyStoreEntity);

    KeyStoreSingletonBean keyStoreSingletonBean = new KeyStoreSingletonBean();

    Field entityManagerField = KeyStoreSingletonBean.class.getDeclaredField("entityManager");
    entityManagerField.setAccessible(true);
    entityManagerField.set(keyStoreSingletonBean, entityManager);

    KeyStoreLoaderBean keyStoreLoaderBean = new KeyStoreLoaderBean();
    Field keyStoreLoaderField = KeyStoreSingletonBean.class.getDeclaredField("keyStoreLoader");
    keyStoreLoaderField.setAccessible(true);
    keyStoreLoaderField.set(keyStoreSingletonBean, keyStoreLoaderBean);

    keyStoreSingletonBean.loadKeys();

    keyStoreSingletonBean.newKeyStore(keyStoreEntity.getId());

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();
    LOG.debug("digest value: " + new String(Hex.encodeHex(digestValue)));
    byte[] signatureValue = keyStoreSingletonBean.sign(keyStoreEntity.getId(), "alias", "SHA-1", digestValue);

    assertNotNull(signatureValue);
    LOG.debug("signature size: " + signatureValue.length);

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(KeyStoreSingletonBeanTest.class.getResourceAsStream("/keystore.p12"), "secret".toCharArray());
    RSAPublicKey publicKey = (RSAPublicKey) keyStore.getCertificate("alias").getPublicKey();

    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger originalBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(originalBigInteger.toByteArray())));

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:org.metaeffekt.dcc.commons.ant.CreateTruststoreTaskTest.java

private void assertValidKeystore(String keystoreFile, String keystoreType, String password, String... aliases)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        FileNotFoundException {//from ww  w . j a v a  2  s  .  com
    KeyStore store = KeyStore.getInstance(keystoreType);
    FileInputStream keystore = new FileInputStream(keystoreFile);
    try {
        store.load(keystore, password.toCharArray());
        for (String alias : aliases) {
            assertNotNull(store.getCertificate(alias));
        }
    } finally {
        IOUtils.closeQuietly(keystore);
    }
}

From source file:test.integ.be.e_contract.mycarenet.sts.RequestFactoryTest.java

@Test
public void testCreateRequest() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);// www  .j av a 2s  . c o  m
    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());

    RequestFactory requestFactory = new RequestFactory();

    List<Attribute> attributes = new LinkedList<Attribute>();
    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<AttributeDesignator>();
    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 requestElement = requestFactory.createRequest(authnCertificate, eHealthPrivateKey,
            eHealthCertificate, attributes, attributeDesignators);

    assertNotNull(requestElement);

    LOG.debug("request: " + toString(requestElement));
}

From source file:password.pwm.http.client.PwmHttpClientTest.java

private X509Certificate getWireMockSelfSignedCertificate() {
    InputStream keystoreInputStream = WireMock.class.getResourceAsStream("/keystore");

    try {//from  www  . jav  a  2 s .  c o  m
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keystoreInputStream, "password".toCharArray());
        return (X509Certificate) keyStore.getCertificate("wiremock");
    } catch (Exception e) {
        fail("Unable to load wiremock self-signed certificate", e);
    }

    return null;
}