Example usage for java.security.cert X509Certificate getEncoded

List of usage examples for java.security.cert X509Certificate getEncoded

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getEncoded.

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

From source file:be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImpl.java

private void validateToken(Element tokenElement, String expectedAudience,
        IdentityProviderConfiguration identityProviderConfiguration) throws Exception {
    List<X509Certificate> certificateChain = identityProviderConfiguration.getIdentityCertificateChain();
    if (certificateChain.isEmpty()) {
        throw new SecurityException("no eID IdP service identity configured");
    }//  w w w . jav  a  2 s  .c  om

    Element nsElement = tokenElement.getOwnerDocument().createElement("nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion");
    LOG.debug("token element: " + tokenElement.getLocalName());
    LOG.debug("token element namespace: " + tokenElement.getNamespaceURI());
    LOG.debug("token: " + toString(tokenElement));

    // fix for recent versions of Apache xmlsec.
    tokenElement.setIdAttribute("ID", true);

    Element signatureElement = (Element) XPathAPI.selectSingleNode(tokenElement, "ds:Signature", nsElement);
    if (null == signatureElement) {
        throw new SecurityException("missing XML signature");
    }

    XMLSignature xmlSignature = new XMLSignature(signatureElement, "");
    KeyInfo keyInfo = xmlSignature.getKeyInfo();
    X509Certificate actualCertificate = keyInfo.getX509Certificate();
    boolean signatureResult = xmlSignature.checkSignatureValue(actualCertificate);
    if (false == signatureResult) {
        throw new SecurityException("invalid XML signature");
    }
    LOG.debug("XML signature OK");

    X509Certificate serviceCertificate = certificateChain.get(0);
    if (false == Arrays.equals(serviceCertificate.getEncoded(), actualCertificate.getEncoded())) {
        throw new SecurityException("SAML signing certificate different from eID IdP service identity");
    }
    LOG.debug("SAML signer OK");

    String actualIssuer = XPathAPI.selectSingleNode(tokenElement, "saml2:Issuer/text()", nsElement)
            .getNodeValue();
    String serviceIssuer = identityProviderConfiguration.getDefaultIssuer();
    if (false == actualIssuer.equals(serviceIssuer)) {
        LOG.debug("actual issuer: " + actualIssuer);
        LOG.debug("service issuer: " + serviceIssuer);
        throw new SecurityException("wrong SAML issuer");
    }
    LOG.debug("SAML issuer OK");

    if (null != expectedAudience) {
        String audience = XPathAPI
                .selectSingleNode(tokenElement,
                        "saml2:Conditions/saml2:AudienceRestriction/saml2:Audience/text()", nsElement)
                .getNodeValue();
        if (false == expectedAudience.equals(audience)) {
            LOG.debug("expected audience: " + expectedAudience);
            LOG.debug("actual audience: " + audience);
            throw new SecurityException("incorrect SAML audience");
        }
        LOG.debug("SAML Audience OK");
    } else {
        LOG.warn("SAML audience restriction not checked");
    }

    String authnContextClassRef = XPathAPI
            .selectSingleNode(tokenElement,
                    "saml2:AuthnStatement/saml2:AuthnContext/saml2:AuthnContextClassRef/text()", nsElement)
            .getNodeValue();
    LOG.debug("AuthnContextClassRef: " + authnContextClassRef);
    SamlAuthenticationPolicy samlAuthenticationPolicy = SamlAuthenticationPolicy
            .getAuthenticationPolicy(authnContextClassRef);
    if (SamlAuthenticationPolicy.AUTHENTICATION != samlAuthenticationPolicy
            && SamlAuthenticationPolicy.AUTHENTICATION_WITH_IDENTIFICATION != samlAuthenticationPolicy) {
        throw new SecurityException("wrong SAML authentication policy: " + samlAuthenticationPolicy);
    }

    String notBeforeStr = XPathAPI.selectSingleNode(tokenElement, "saml2:Conditions/@NotBefore", nsElement)
            .getNodeValue();
    String notOnOrAfterStr = XPathAPI
            .selectSingleNode(tokenElement, "saml2:Conditions/@NotOnOrAfter", nsElement).getNodeValue();
    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser();
    DateTime notBefore = dateTimeFormatter.parseDateTime(notBeforeStr);
    DateTime notOnOrAfter = dateTimeFormatter.parseDateTime(notOnOrAfterStr);
    DateTime now = new DateTime();
    if (now.isBefore(notBefore)) {
        throw new SecurityException("SAML assertion in future");
    }
    if (now.isAfter(notOnOrAfter)) {
        throw new SecurityException("SAML assertion expired");
    }
    LOG.debug("SAML timestamp OK");
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Convert a KeyStore to PEM format.// w ww  .  ja va  2s  .c  o m
 */
public static byte[] getSinglePemFromKeyStore(final KeyStore ks, final char[] password)
        throws KeyStoreException, CertificateEncodingException, IOException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    // Find the key private key entry in the keystore
    final Enumeration<String> e = ks.aliases();
    Object o = null;
    String alias = "";
    PrivateKey serverPrivKey = null;
    while (e.hasMoreElements()) {
        o = e.nextElement();
        if (o instanceof String) {
            if ((ks.isKeyEntry((String) o))
                    && ((serverPrivKey = (PrivateKey) ks.getKey((String) o, password)) != null)) {
                alias = (String) o;
                break;
            }
        }
    }

    byte[] privKeyEncoded = "".getBytes();

    if (serverPrivKey != null) {
        privKeyEncoded = serverPrivKey.getEncoded();
    }

    final Certificate[] chain = KeyTools.getCertChain(ks, (String) o);
    final X509Certificate userX509Certificate = (X509Certificate) chain[0];

    final byte[] output = userX509Certificate.getEncoded();
    String sn = CertTools.getSubjectDN(userX509Certificate);

    String subjectdnpem = sn.replace(',', '/');
    String issuerdnpem = CertTools.getIssuerDN(userX509Certificate).replace(',', '/');

    buffer.write(BAG_ATTRIBUTES);
    buffer.write(FRIENDLY_NAME);
    buffer.write(alias.getBytes());
    buffer.write(NL);
    buffer.write(BEGIN_PRIVATE_KEY);
    buffer.write(NL);

    final byte[] privKey = Base64.encode(privKeyEncoded);
    buffer.write(privKey);
    buffer.write(NL);
    buffer.write(END_PRIVATE_KEY);
    buffer.write(NL);
    buffer.write(BAG_ATTRIBUTES);
    buffer.write(FRIENDLY_NAME);
    buffer.write(alias.getBytes());
    buffer.write(NL);
    buffer.write(SUBJECT_ATTRIBUTE);
    buffer.write(subjectdnpem.getBytes());
    buffer.write(NL);
    buffer.write(ISSUER_ATTRIBUTE);
    buffer.write(issuerdnpem.getBytes());
    buffer.write(NL);
    buffer.write(BEGIN_CERTIFICATE);
    buffer.write(NL);

    final byte[] userCertB64 = Base64.encode(output);
    buffer.write(userCertB64);
    buffer.write(NL);
    buffer.write(END_CERTIFICATE);
    buffer.write(NL);

    if (!CertTools.isSelfSigned(userX509Certificate)) {
        for (int num = 1; num < chain.length; num++) {
            final X509Certificate tmpX509Cert = (X509Certificate) chain[num];
            sn = CertTools.getSubjectDN(tmpX509Cert);

            String cn = CertTools.getPartFromDN(sn, "CN");
            if (StringUtils.isEmpty(cn)) {
                cn = "Unknown";
            }

            subjectdnpem = sn.replace(',', '/');
            issuerdnpem = CertTools.getIssuerDN(tmpX509Cert).replace(',', '/');

            buffer.write(BAG_ATTRIBUTES);
            buffer.write(FRIENDLY_NAME);
            buffer.write(cn.getBytes());
            buffer.write(NL);
            buffer.write(SUBJECT_ATTRIBUTE);
            buffer.write(subjectdnpem.getBytes());
            buffer.write(NL);
            buffer.write(ISSUER_ATTRIBUTE);
            buffer.write(issuerdnpem.getBytes());
            buffer.write(NL);

            final byte[] tmpOutput = tmpX509Cert.getEncoded();
            buffer.write(BEGIN_CERTIFICATE);
            buffer.write(NL);

            final byte[] tmpCACertB64 = Base64.encode(tmpOutput);
            buffer.write(tmpCACertB64);
            buffer.write(NL);
            buffer.write(END_CERTIFICATE);
            buffer.write(NL);
        }
    }
    return buffer.toByteArray();
}

From source file:be.fedict.eid.idp.model.bean.IdentityServiceBean.java

/**
 * {@inheritDoc}//ww  w.  j  av a2s  . c  om
 */
public String getIdentityFingerprint() {
    IdPIdentity identity = findIdentity();
    if (null == identity) {
        return null;
    }
    X509Certificate certificate = (X509Certificate) identity.getPrivateKeyEntry().getCertificate();
    if (null == certificate) {
        return null;
    }
    String fingerprint;
    try {
        fingerprint = DigestUtils.shaHex(certificate.getEncoded());
    } catch (CertificateEncodingException e) {
        return null;
    }
    return fingerprint;
}

From source file:org.apli.modelbeans.facturacion.cfdi.CFDv32.java

@Override
public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
    cert.checkValidity();/*from  ww w. j av a 2 s .  c o m*/
    String signature = getSignature(key);
    document.setSello(signature);
    byte[] bytes = cert.getEncoded();
    Base64 b64 = new Base64(-1);
    String certStr = b64.encodeToString(bytes);
    document.setCertificado(certStr);
    BigInteger bi = cert.getSerialNumber();
    document.setNoCertificado(new String(bi.toByteArray()));
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

@Test
public void testPersonUserCertLoginIncorrectCert() throws Exception {
    X509Certificate cert = TENANT_CERT;
    byte[] certBytes = cert.getEncoded();
    String certString64 = Base64Utils.encodeToString(certBytes);
    assertErrorResponseUsingPersonUserCert(certString64, null, (Cookie) null,
            "access_denied: invalid person user cert");
}

From source file:org.apache.directory.studio.connection.core.StudioKeyStoreManager.java

private void addToKeyStore(X509Certificate certificate, KeyStore keyStore) throws Exception {
    // The alias is not relevant, it just needs to be an unique identifier.
    // The SHA-1 hash of the certificate should be unique.
    byte[] encoded = certificate.getEncoded();
    String shaHex = DigestUtils.shaHex(encoded);
    keyStore.setCertificateEntry(shaHex, certificate);
}

From source file:org.holistic.ws_proxy.WSProxyHelper.java

public void set_headers2urlconn(HttpServletRequest req, URLConnection objURLConn) throws Exception {
    String m_strName;//from   ww w. ja v a 2s.  c o m
    String m_strValue;
    for (Enumeration m_objElement = req.getHeaderNames(); m_objElement.hasMoreElements(); log
            .debug("ClientToEndPoint HEADER[" + m_strName + "] - VALUE[" + m_strValue + "]")) {
        m_strName = (String) m_objElement.nextElement();
        m_strValue = req.getHeader(m_strName);
        if (m_strName.toUpperCase().equals("COOKIE") && m_strValue.indexOf(COOKIE_SESSION + "=") > 0)
            m_strValue = m_strValue.replaceAll(COOKIE_SESSION + "=", COOKIE_SESSION + "_PROXY=");
        if (m_strName.toUpperCase().equals("COOKIE") && m_strValue.indexOf(EXTRA_COOKIE) > 0)
            m_strValue = m_strValue.replaceAll(EXTRA_COOKIE, "");
        objURLConn.setRequestProperty(m_strName, m_strValue);
    }

    String m_RemoteAddr = req.getRemoteAddr();
    objURLConn.setRequestProperty("x-forwarded-for", m_RemoteAddr);
    log.debug("Client IP x-forwarded-for (" + m_RemoteAddr + ").");
    String cipherSuite = (String) req.getAttribute("javax.net.ssl.cipher_suite");
    if (cipherSuite != null && req.getAttribute("javax.net.ssl.peer_certificates") != null) {
        java.security.cert.X509Certificate certChain[] = (java.security.cert.X509Certificate[]) req
                .getAttribute("javax.net.ssl.peer_certificates");
        java.security.cert.X509Certificate certStandar = certChain[0];
        m_strName = "entrust-client-certificate";
        String m_strTemp = (new BASE64Encoder()).encode(certStandar.getEncoded());
        m_strValue = m_strTemp.replaceAll("\r\n", "").replaceAll("\n", "");
        objURLConn.setRequestProperty(m_strName, m_strValue);
        log.debug("HEADER[" + m_strName + "] - VALUE[" + m_strValue + "]");
    }
}

From source file:com.netscape.cmstools.pkcs7.PKCS7CertExportCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args, true);

    if (cmd.hasOption("help")) {
        printHelp();//ww w .  j a va 2  s . c o  m
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String filename = cmd.getOptionValue("pkcs7-file");

    if (filename == null) {
        throw new Exception("Missing PKCS #7 file.");
    }

    logger.info("Loading PKCS #7 data from " + filename);
    String str = new String(Files.readAllBytes(Paths.get(filename))).trim();
    PKCS7 pkcs7 = new PKCS7(str);

    X509Certificate[] certs = pkcs7.getCertificates();
    if (certs == null || certs.length == 0) {
        System.out.println("PKCS #7 data contains no certificates");
        return;
    }

    // sort certs from root to leaf
    certs = CryptoUtil.sortCertificateChain(certs);

    String prefix = cmd.getOptionValue("output-prefix", filename + "-");
    String suffix = cmd.getOptionValue("output-suffix", "");
    int i = 0;

    for (X509Certificate cert : certs) {

        logger.info("Exporting certificate #" + i + ": " + cert.getSubjectDN());

        String output = prefix + i + suffix;

        try (PrintWriter out = new PrintWriter(new FileWriter(output))) {
            out.println(Cert.HEADER);
            out.print(Utils.base64encode(cert.getEncoded(), true));
            out.println(Cert.FOOTER);
        }

        System.out.println(output + ": " + cert.getSubjectDN());

        i++;
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.LTVEnabledPADESPDFBOXSigner.java

/**
 * Adds the "Certs" dictionary to DSS dictionary as specified in <a href=
 * "http://www.etsi.org/deliver/etsi_ts%5C102700_102799%5C10277804%5C01.01.02_60%5Cts_10277804v010102p.pdf">PAdES
 * ETSI TS 102 778-4 v1.1.2, Annex A, "LTV extensions"</a>.
 *
 * @param pdDocument//from   www  . j a  v  a2 s  . co m
 *            The pdf document (required; must not be {@code null}).
 * @param dssDictionary
 *            The DSS dictionary (required; must not be {@code null}).
 * @param certificates
 *            The certificates (required; must not be {@code null}).
 * @throws IOException
 *             In case there was an error adding a pdf stream to the document.
 * @throws CertificateEncodingException
 *             In case of an error encoding certificates.
 */
private void addDSSCerts(PDDocument pdDocument, COSDictionary dssDictionary,
        Iterable<X509Certificate> certificates) throws IOException, CertificateEncodingException {
    final COSName COSNAME_CERTS = COSName.getPDFName("Certs");
    COSArray certsArray = (COSArray) Objects.requireNonNull(dssDictionary).getDictionaryObject(COSNAME_CERTS);
    if (certsArray == null) {
        // add new "Certs" array
        log.trace("Adding new DSS/Certs dictionary.");
        // "An array of (indirect references to) streams, each containing one BER-encoded X.509 certificate (see RFC 5280 [7])"
        certsArray = new COSArray();
        dssDictionary.setItem(COSNAME_CERTS, certsArray);
    }
    certsArray.setNeedToBeUpdate(true);

    // add BER-encoded X.509 certificates
    log.trace("Adding certificates to DSS/Certs dictionary.");
    for (X509Certificate certificate : certificates) {
        log.trace("Adding certificate for subject: {}", certificate.getSubjectDN());
        try (InputStream in = new ByteArrayInputStream(certificate.getEncoded())) {
            PDStream pdStream = new PDStream(pdDocument, in);
            pdStream.addCompression();
            certsArray.add(pdStream);
        }
    }
}

From source file:org.wso2.carbon.identity.certificateauthority.endpoint.scep.ScepEndpoint.java

private Response getCaCert(String tenantId) {
    try {/*from  w  w  w.  j a  va 2s .  c  o  m*/
        int tId = Integer.parseInt(tenantId);
        X509Certificate caCert = scepServices.getCaCert(tId);
        if (caCert != null) {
            Response.ok().type("application/x-x509-ca-cert").entity(caCert.getEncoded());
        }
    } catch (NumberFormatException e) {
        return ResponseUtils.notFound();
    } catch (CertificateEncodingException e) {
        return ResponseUtils.serverError();
    } catch (Exception e) {
        //occurs when invalid tenant id is given
        log.warn("Certificate for tenant " + tenantId + " is requested, but was not available");
        return ResponseUtils.notFound();
    }
    return ResponseUtils.notFound();
}