Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:ru.codeinside.gws3572c.GMPClientSignTest.java

@Test
public void testSignForEntity() throws Exception {
    ClientRequest request = client.createClientRequest(createContext());
    InputSource is = new InputSource(new StringReader(request.appData));
    Document doc = documentBuilder.parse(is);

    Element elementForSign = (Element) doc.getElementsByTagNameNS(null, "Charge").item(0);

    Node parentNode;// w ww  .  ja  v  a  2 s  . c o m
    Document detachedDocument;
    if (!elementForSign.isSameNode(doc.getDocumentElement())) {
        parentNode = elementForSign.getParentNode();
        parentNode.removeChild(elementForSign);

        detachedDocument = documentBuilder.newDocument();
        Node importedElementForSign = detachedDocument.importNode(elementForSign, true);
        detachedDocument.appendChild(importedElementForSign);
    } else {
        detachedDocument = doc;
    }

    Element nscontext = detachedDocument.createElementNS(null, "namespaceContext");
    nscontext.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + "ds".trim(),
            "http://www.w3.org/2000/09/xmldsig#");

    Element certificateElement = (Element) XPathAPI.selectSingleNode(detachedDocument,
            "//ds:X509Certificate[1]", nscontext);
    Element sigElement = (Element) certificateElement.getParentNode().getParentNode().getParentNode();

    XMLSignature signature = new XMLSignature(sigElement, "");

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate certKey = (X509Certificate) cf.generateCertificate(
            new ByteArrayInputStream(Base64.decode(certificateElement.getTextContent().trim().getBytes())));

    Assert.assertNotNull("There are no information about public key. Verification couldn't be implemented",
            certKey);
    Assert.assertTrue("Signature is not valid", signature.checkSignatureValue(certKey));
}

From source file:wssec.TestWSSecurityWSS86.java

/**
 * Test loading a certificate using BouncyCastle, and using it to encrypt a message, but
 * decrypt the message using the Java Keystore provider
 *///from  w ww .ja  v  a2s  .co  m
public void testInterop() throws Exception {
    // 
    // This cert corresponds to the cert in wss86.keystore
    // Extracted with:
    // keytool -export -rfc -keystore wss86.keystore -alias wss86 -file wss86.cer
    //
    byte[] certBytes = org.apache.ws.security.util.Base64
            .decode("MIICfDCCAeUCBEnHoGMwDQYJKoZIhvcNAQEEBQAwgYQxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIEwZC"
                    + "YXllcm4xDzANBgNVBAcTBk11bmljaDEPMA0GA1UEChMGQXBhY2hlMQ4wDAYDVQQLEwVXU1M0SjEP"
                    + "MA0GA1UEAxMGV2VybmVyMSEwHwYJKoZIhvcNAQkBFhJXZXJuZXJAZXhhbXBsZS5jb20wHhcNMDkw"
                    + "MzIzMTQ0NDUxWhcNMTkwMzIxMTQ0NDUxWjCBhDELMAkGA1UEBhMCREUxDzANBgNVBAgTBkJheWVy"
                    + "bjEPMA0GA1UEBxMGTXVuaWNoMQ8wDQYDVQQKEwZBcGFjaGUxDjAMBgNVBAsTBVdTUzRKMQ8wDQYD"
                    + "VQQDEwZXZXJuZXIxITAfBgkqhkiG9w0BCQEWEldlcm5lckBleGFtcGxlLmNvbTCBnzANBgkqhkiG"
                    + "9w0BAQEFAAOBjQAwgYkCgYEA3uRplw7q8y/sIR541uCrlbIMzJHXCRU3nQreGNr6dM49/LxHYffQ"
                    + "Ex99chQh+wR6fwArFlziDRNnqslOy8zKMfGbaBaR41ZZrxvkSsIwzOhD6yAPgKVQL2vTmJAbdZ35"
                    + "GwcOW8oe7l+NV9qmv7yrr5OhqDhFh36WhgjVLiwmP/cCAwEAATANBgkqhkiG9w0BAQQFAAOBgQBP"
                    + "PnR2BYn7DKn/SkU8XTgf9g2NoYcMyvQOB+Uo25/QzDdMk6HKmHl0+7mh7RAtXcBz2YqC3WbQW5U3"
                    + "KmOH6fVxB8hw6xalBjs2YpnBx4gaHAws35KlAfkGVVe5wqnrI7ER7RBYO/7Gr7uCUq11QrGyEG8/"
                    + "yIXktaFLxgD2R4hpfA==");
    CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate cert = (X509Certificate) factory
            .generateCertificate(new java.io.ByteArrayInputStream(certBytes));

    SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
    WSSecEncrypt encrypt = new WSSecEncrypt();
    encrypt.setUseThisCert(cert);
    Document doc = unsignedEnvelope.getAsDocument();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document encryptedDoc = encrypt.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
        LOG.debug(outputString);
    }
    verify(encryptedDoc);

}

From source file:com.google.appengine.tck.appidentity.AppIdentityServiceTest.java

private boolean verifySignatureWithAllCertsForApp(byte[] blob, byte[] signedBlob,
        Collection<PublicCertificate> certsForApp) {

    if (certsForApp.isEmpty()) {
        throw new IllegalStateException("No certificates to validate.  Must have at least 1.");
    }/*from w w  w . j  a va 2 s .  co m*/
    int currentCertNum = 0;
    int totalValid = 0;
    int totalInvalid = 0;
    List<Exception> allExceptions = new ArrayList<>();

    for (PublicCertificate publicCert : certsForApp) {
        Signature signature;
        Certificate cert = null;
        currentCertNum++;

        log.info("Processing certNum:" + currentCertNum);
        try {
            byte[] certBytes = publicCert.getX509CertificateInPemFormat().getBytes("UTF-8");
            InputStream stream = new ByteArrayInputStream(certBytes);
            signature = Signature.getInstance("SHA256withRSA"); // Make this configurable?
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            cert = cf.generateCertificate(stream);
            log.info(cert.toString());

            PublicKey pk = cert.getPublicKey();
            signature.initVerify(pk);
            signature.update(blob);
            boolean isValidSignature = signature.verify(signedBlob);

            if (isValidSignature) {
                totalValid++;
            } else {
                totalInvalid++;
            }
            log.info("certNum:" + currentCertNum + ": is valid:" + isValidSignature);

            // These can be thrown:
            // UnsupportedEncodingException, NoSuchAlgorithmException, CertificateException,
            // SignatureException, InvalidKeyException
        } catch (Exception e) {
            Exception logException = createExceptionForLog(e, currentCertNum, cert);
            allExceptions.add(logException);
            log.info(e.toString());
        }
    }
    String summary = "totalCerts:" + certsForApp.size() + ": totalValid:" + totalValid + " totalInvalid:"
            + totalInvalid + " totalExceptions:" + allExceptions.size();
    log.info(summary);

    // At least one certificate caused an exception so make test Error.
    if (allExceptions.size() > 0) {
        throw new IllegalStateException(summary + "\n\n" + exceptionListToString(allExceptions));
    }

    // At least one signature was valid and no exceptions thrown.
    return (totalValid > 0);
}

From source file:org.kuali.rice.ksb.messaging.KSBHttpInvokerRequestExecutor.java

/**
 * Returns a wrapped InputStream which is responsible for verifying the digital signature on the response after all
 * data has been read./*from  w ww  . j  a va 2s.c o  m*/
 */
@Override
protected InputStream getResponseBody(HttpInvokerClientConfiguration config, HttpResponse postMethod)
        throws IOException {
    if (isSecure()) {
        // extract and validate the headers
        Header digitalSignatureHeader = postMethod.getFirstHeader(KSBConstants.DIGITAL_SIGNATURE_HEADER);
        Header keyStoreAliasHeader = postMethod.getFirstHeader(KSBConstants.KEYSTORE_ALIAS_HEADER);
        Header certificateHeader = postMethod.getFirstHeader(KSBConstants.KEYSTORE_CERTIFICATE_HEADER);

        if (digitalSignatureHeader == null || StringUtils.isEmpty(digitalSignatureHeader.getValue())) {
            throw new RuntimeException(
                    "A digital signature header was required on the response but none was found.");
        }

        boolean foundValidKeystoreAlias = (keyStoreAliasHeader != null
                && StringUtils.isNotBlank(keyStoreAliasHeader.getValue()));
        boolean foundValidCertificate = (certificateHeader != null
                && StringUtils.isNotBlank(certificateHeader.getValue()));

        if (!foundValidCertificate && !foundValidKeystoreAlias) {
            throw new RuntimeException(
                    "Either a key store alias header or a certificate header was required on the response but neither were found.");
        }

        // decode the digital signature from the header into binary
        byte[] digitalSignature = Base64.decodeBase64(digitalSignatureHeader.getValue().getBytes("UTF-8"));
        String errorQualifier = "General Security Error";

        try {
            Signature signature = null;

            if (foundValidCertificate) {
                errorQualifier = "Error with given certificate";
                // get the Signature for verification based on the alias that was sent to us
                byte[] encodedCertificate = Base64.decodeBase64(certificateHeader.getValue().getBytes("UTF-8"));
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                signature = getDigitalSignatureService().getSignatureForVerification(
                        cf.generateCertificate(new ByteArrayInputStream(encodedCertificate)));
            } else if (foundValidKeystoreAlias) {
                // get the Signature for verification based on the alias that was sent to us
                String keystoreAlias = keyStoreAliasHeader.getValue();
                errorQualifier = "Error with given alias " + keystoreAlias;
                signature = getDigitalSignatureService().getSignatureForVerification(keystoreAlias);
            }

            // wrap the InputStream in an input stream that will verify the signature
            return new SignatureVerifyingInputStream(digitalSignature, signature,
                    super.getResponseBody(config, postMethod));
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("Problem verifying signature: " + errorQualifier, e);
        }
    }

    return super.getResponseBody(config, postMethod);
}

From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java

private X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, DateTime notBefore,
        DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) throws Exception {

    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();/*  ww w. j a v  a2  s.  co  m*/
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());

    X509Principal issuerDN;
    if (null != issuerCertificate) {
        issuerDN = new X509Principal(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        issuerDN = new X509Principal(subjectDn);
    }
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));

    PublicKey issuerPublicKey;
    if (null != issuerCertificate) {
        issuerPublicKey = issuerCertificate.getPublicKey();
    } else {
        issuerPublicKey = subjectPublicKey;
    }
    certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerPublicKey));

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
}

From source file:org.apache.tomcat.util.net.jsse.JSSE14Support.java

/** Return the X509certificates or null if we can't get them.
 *  XXX We should allow unverified certificates 
 *///from  ww  w  .ja  v  a2s  . c om
protected X509Certificate[] getX509Certificates(SSLSession session) throws IOException {
    Certificate[] certs = null;
    try {
        certs = session.getPeerCertificates();
    } catch (Throwable t) {
        logger.debug("Error getting client certs", t);
        return null;
    }
    if (certs == null)
        return null;

    X509Certificate[] x509Certs = new X509Certificate[certs.length];
    for (int i = 0; i < certs.length; i++) {
        if (certs[i] instanceof X509Certificate) {
            // always currently true with the JSSE 1.1.x
            x509Certs[i] = (X509Certificate) certs[i];
        } else {
            try {
                byte[] buffer = certs[i].getEncoded();
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
                x509Certs[i] = (X509Certificate) cf.generateCertificate(stream);
            } catch (Exception ex) {
                logger.info("Error translating cert " + certs[i], ex);
                return null;
            }
        }
        if (logger.isTraceEnabled())
            logger.trace("Cert #" + i + " = " + x509Certs[i]);
    }
    if (x509Certs.length < 1)
        return null;
    return x509Certs;
}

From source file:com.puppetlabs.geppetto.puppetdb.impl.PuppetDBConnectionPreferencesImpl.java

private Certificate generateCertificate(String prefName, CertificateFactory factory)
        throws CertificateException, IOException {
    try {/*from  w  w  w . java  2s .  c o  m*/
        String certString = getPreference(prefName);
        return certString == null ? null
                : factory.generateCertificate(new ByteArrayInputStream(certString.getBytes(ASCII)));
    } catch (BackingStoreException e) {
        throw new IOException(e);
    }
}

From source file:be.e_contract.eid.applet.service.impl.handler.IdentityDataMessageHandler.java

/**
 * Tries to parse the X509 certificate.//from ww w.j a  v  a 2  s .  c o m
 * 
 * @param certFile
 * @return the X509 certificate, or <code>null</code> in case of a DER
 *         decoding error.
 */
private X509Certificate getCertificate(byte[] certFile) {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certFile));
        return certificate;
    } catch (CertificateException e) {
        LOG.warn("certificate error: " + e.getMessage(), e);
        LOG.debug("certificate size: " + certFile.length);
        LOG.debug("certificate file content: " + Hex.encodeHexString(certFile));
        /*
         * Missing eID authentication and eID non-repudiation certificates
         * could become possible for future eID cards. A missing certificate
         * is represented as a block of 1300 null bytes.
         */
        if (1300 == certFile.length) {
            boolean missingCertificate = true;
            for (int idx = 0; idx < certFile.length; idx++) {
                if (0 != certFile[idx]) {
                    missingCertificate = false;
                }
            }
            if (missingCertificate) {
                LOG.debug("the certificate data indicates a missing certificate");
            }
        }
        return null;
    }
}

From source file:mitm.common.hibernate.CertificateArrayUserType.java

private Certificate cloneCertificate(Certificate original)
        throws CertificateException, NoSuchProviderException, SecurityFactoryFactoryException {
    byte[] encodedCert = original.getEncoded();

    String certificateType = original.getType();

    CertificateFactory factory = SecurityFactoryFactory.getSecurityFactory()
            .createCertificateFactory(certificateType);

    Certificate copy = factory.generateCertificate(new ByteArrayInputStream(encodedCert));

    return copy;//from   w w  w.  j  a v  a 2 s.  c o  m
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

private X509Certificate getCertificate(String certificate) {
    if (certificate.isEmpty()) {
        return null;
    }/*w w w.ja v a  2s  .c  o m*/

    if (certificate.contains(KeyStoreConstant.BEGIN_CERTIFICATE)) {
        final int fIdx = certificate.indexOf(KeyStoreConstant.BEGIN_CERTIFICATE)
                + KeyStoreConstant.BEGIN_CERTIFICATE.length();
        final int sIdx = certificate.indexOf(KeyStoreConstant.END_CERTIFICATE);
        certificate = certificate.substring(fIdx, sIdx);
    }
    final byte[] byteCert = Base64.decodeBase64(certificate);
    final InputStream inputStreamCert = new ByteArrayInputStream(byteCert);
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate newCert = (X509Certificate) certFactory.generateCertificate(inputStreamCert);
        newCert.checkValidity();
        return newCert;
    } catch (final CertificateException e) {
        LOG.error("Failed to get certificate {}", e.getMessage());
        return null;
    }
}