Example usage for org.bouncycastle.asn1.x500 X500Name X500Name

List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x500 X500Name X500Name.

Prototype

public X500Name(String dirName) 

Source Link

Usage

From source file:eu.eidas.auth.engine.core.impl.EncryptionSW.java

License:EUPL

@Override
public Response encryptSAMLResponse(Response authResponse, String destinationCountryCode, String requestIssuer,
        String messageFormat) throws SAMLEngineException {
    BasicX509Credential credential = (BasicX509Credential) getMetadataEncryptionCredential(requestIssuer,
            messageFormat);/*from w w  w  .  j a  v a2  s .com*/
    if (credential == null && isEncryptionEnable(destinationCountryCode)) {
        LOG.debug("Encryption enable, proceeding...");
        StringBuilder issuerKey = new StringBuilder(RESPONSE_TO_POINT_ISSUER).append(".")
                .append(destinationCountryCode);
        StringBuilder serialNumberKey = new StringBuilder("responseToPointSerialNumber").append(".")
                .append(destinationCountryCode);
        final String serialNumber = properties.getProperty(serialNumberKey.toString());
        final String responseToPointIssuer = properties.getProperty(issuerKey.toString());
        if (responseToPointIssuer != null && !responseToPointIssuer.isEmpty()) {
            try {
                String aliasCert;
                String alias = null;
                X509Certificate responsePointAliasCert = null;
                boolean find = false;

                for (final Enumeration<String> e = encryptionKeyStore.aliases(); e.hasMoreElements()
                        && !find;) {
                    aliasCert = e.nextElement();
                    responsePointAliasCert = (X509Certificate) encryptionKeyStore.getCertificate(aliasCert);

                    final String serialNum = responsePointAliasCert.getSerialNumber().toString(16);

                    X500Name issuerDN = new X500Name(responsePointAliasCert.getIssuerDN().getName());
                    X500Name issuerDNConf = new X500Name(responseToPointIssuer);

                    if (serialNum.equalsIgnoreCase(serialNumber)
                            && X500PrincipalUtil.principalEquals(issuerDN, issuerDNConf)) {
                        alias = aliasCert;
                        find = true;
                    }
                }
                if (!find) {
                    throw new SAMLEngineException(EIDASErrors.SAML_ENGINE_INVALID_CERTIFICATE.errorCode(),
                            EIDASErrors.SAML_ENGINE_INVALID_CERTIFICATE.errorMessage());
                }
                // Find configured certificate
                responsePointAliasCert = (X509Certificate) encryptionKeyStore.getCertificate(alias);
                checkCertificateValidityPeriod(responsePointAliasCert);
                checkCertificateIssuer(responsePointAliasCert);
                // Create basic credential and set the EntityCertificate
                credential = new BasicX509Credential();
                credential.setEntityCertificate(responsePointAliasCert);
            } catch (KeyStoreException kse) {
                throw new SAMLEngineException(EIDASErrors.SAML_ENGINE_INVALID_KEYSTORE.errorCode(),
                        EIDASErrors.SAML_ENGINE_INVALID_KEYSTORE.errorMessage(), kse);
            } catch (Exception e) {
                LOG.warn("Error encrypting SAML Response.", e.getMessage());
                throw new SAMLEngineException(e);
            } finally {
                LOG.debug("Credential for encryption of SAML Response done for target: '"
                        + responseToPointIssuer + "'");
            }
        } else {
            LOG.error("Encryption of SAML Response NOT done, because no " + RESPONSE_TO_POINT_ISSUER + " "
                    + "configured!");
        }
    }
    if (isEncryptionEnable(destinationCountryCode)) {
        if (credential == null) {
            throw new SAMLEngineException(EIDASErrors.SAML_ENGINE_UNENCRYPTED_RESPONSE.errorCode(),
                    EIDASErrors.SAML_ENGINE_UNENCRYPTED_RESPONSE.errorMessage());
        }
        try {
            // Execute encryption
            return samlAuthnResponseEncrypter.encryptSAMLResponse(authResponse, credential);
        } catch (EncryptionException e) {
            LOG.info("ERROR : Error encrypting SAML Response.", e.getMessage());
            throw new SAMLEngineException(e);
        } finally {
            LOG.debug("Encryption of SAML Response done for target: "
                    + credential.getEntityCertificate().getIssuerDN());
        }

    }
    return authResponse;
}

From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java

License:EUPL

/**
 * Gets the alias from X.509 Certificate at keystore.
 * /*from w  w  w.j  a  va  2  s  .c  o m*/
 * @param keyInfo the key info
 * @param ownKeyStore 
 * @param ownKeyStore 
 * 
 * @return the alias
 */
private String getAlias(final KeyInfo keyInfo, KeyStore ownKeyStore) {

    LOG.trace("Recover alias information");

    String alias = null;
    try {
        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        // Transform the KeyInfo to X509Certificate.
        CertificateFactory certFact;
        certFact = CertificateFactory.getInstance("X.509");

        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));

        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        final String tokenSerialNumber = cert.getSerialNumber().toString(HEXA);
        final X500Name tokenIssuerDN = new X500Name(cert.getIssuerDN().getName());

        String aliasCert;
        X509Certificate certificate;
        boolean find = false;

        for (final Enumeration<String> e = ownKeyStore.aliases(); e.hasMoreElements() && !find;) {
            aliasCert = e.nextElement();
            certificate = (X509Certificate) ownKeyStore.getCertificate(aliasCert);

            final String serialNum = certificate.getSerialNumber().toString(HEXA);

            X500Name issuerDN = new X500Name(certificate.getIssuerDN().getName());

            if (serialNum.equalsIgnoreCase(tokenSerialNumber)
                    && X500PrincipalUtil.principalEquals(issuerDN, tokenIssuerDN)) {
                alias = aliasCert;
                find = true;
            }

        }

    } catch (KeyStoreException e) {
        LOG.info(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e.getMessage());
        LOG.debug(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e);
    } catch (CertificateException e) {
        LOG.info(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e.getMessage());
        LOG.debug(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e);
    } catch (RuntimeException e) {
        LOG.info(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e.getMessage());
        LOG.debug(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e);
    }
    return alias;
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

License:EUPL

/**
 *
 * @param keystore//w w w.  j  a v a  2s  .  c o  m
 * @param serialNumber
 * @param issuer
 * @return a certificate/alias pair from the keystore, having the given issuer and serialNumber
 * @throws KeyStoreException
 * @throws SAMLEngineException
 */
public static CertificateAliasPair getCertificatePair(KeyStore keystore, String serialNumber, String issuer)
        throws KeyStoreException, SAMLEngineException {
    String alias = null;
    String aliasCert;
    X509Certificate certificate;
    boolean find = false;
    LOG.debug("cherche dans " + keystore.toString() + " numSerie=" + serialNumber + " issuer=" + issuer);
    for (final Enumeration<String> e = keystore.aliases(); e.hasMoreElements() && !find;) {
        aliasCert = e.nextElement();
        certificate = (X509Certificate) keystore.getCertificate(aliasCert);

        final String serialNum = certificate.getSerialNumber().toString(16);

        Principal p = certificate.getIssuerDN();
        String name = p.getName();

        X500Name issuerDN = new X500Name(name);
        X500Name issuerDNConf = new X500Name(issuer);

        if (serialNum.equalsIgnoreCase(serialNumber)
                && X500PrincipalUtil.principalEquals(issuerDN, issuerDNConf)) {
            alias = aliasCert;
            find = true;
        } else {
            LOG.debug("pas pareil numSerie=" + serialNum + " ou issuer=" + name);
        }
    }
    if (!find) {
        throw new SAMLEngineException(
                "Certificate " + issuer + "/" + serialNumber + " cannot be found in keystore ");
    }
    certificate = (X509Certificate) keystore.getCertificate(alias);
    return new CertificateAliasPair(certificate, alias);

}

From source file:eu.eidas.engine.test.simple.SimpleBaseTest.java

License:EUPL

@Test
public final void testX509PrincipalsUtils() {
    System.out.println("*********************************************");
    X500Name test1 = new X500Name("C=AU,ST=Victoria");
    X500Name test2 = new X500Name(
            "CN=Thawte Timestamping CA, OU=Thawte Certification, O=Thawte, L=Durbanville, ST=Western Cape, C=ZA");
    Assert.assertTrue(X500PrincipalUtil.principalNotNullEquals(test2, test2));
    Assert.assertFalse(X500PrincipalUtil.principalNotNullEquals(null, null));
    Assert.assertFalse(X500PrincipalUtil.principalNotNullEquals(test2, null));
    Assert.assertFalse(X500PrincipalUtil.principalNotNullEquals(null, test2));
    Assert.assertFalse(X500PrincipalUtil.principalNotNullEquals(test1, test2));
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileC.java

License:Open Source License

/**
 * Create a reference to a X509CRL//from   www .  j  av  a2 s . co  m
 * 
 * @param crl
 * @return
 * @throws NoSuchAlgorithmException
 * @throws CRLException
 */
private CrlValidatedID makeCrlValidatedID(X509CRL crl) throws NoSuchAlgorithmException, CRLException {
    MessageDigest sha1digest = MessageDigest.getInstance(X509ObjectIdentifiers.id_SHA1.getId(),
            new BouncyCastleProvider());
    OtherHash hash = new OtherHash(sha1digest.digest(crl.getEncoded()));
    BigInteger crlnumber;
    CrlIdentifier crlid;
    if (crl.getExtensionValue("2.5.29.20") != null) {
        crlnumber = new DERInteger(crl.getExtensionValue("2.5.29.20")).getPositiveValue();
        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()),
                new DERUTCTime(crl.getThisUpdate()), crlnumber);
    } else {
        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()),
                new DERUTCTime(crl.getThisUpdate()));
    }

    CrlValidatedID crlvid = new CrlValidatedID(hash, crlid);

    return crlvid;
}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

License:Open Source License

@Override
public X509Certificate getSigningCertificate() {
    try {/*  w w w .j  av  a2s.  co m*/
        NodeList list = XMLUtils.getNodeList(signatureElement,
                "./ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/"
                        + "xades:SigningCertificate/xades:Cert");

        for (int i = 0; i < list.getLength(); i++) {
            Element el = (Element) list.item(i);
            Element issuerSubjectNameEl = XMLUtils.getElement(el, "./xades:IssuerSerial/ds:X509IssuerName");
            X500Name issuerName = new X500Name(issuerSubjectNameEl.getTextContent());
            for (X509Certificate c : getCertificateSource().getCertificates()) {
                X500Name cIssuer = new X500Name(c.getIssuerX500Principal().getName());
                if (cIssuer.equals(issuerName)) {
                    return c;
                }
            }
        }

        return null;
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.SIGNING_CERTIFICATE_ENCODING);
    }
}

From source file:eu.europa.esig.dss.test.gen.CertificateService.java

License:Open Source License

public MockPrivateKeyEntry generateCertificateChain(final SignatureAlgorithm algorithm,
        final MockPrivateKeyEntry rootEntry, Date notBefore, Date notAfter) throws Exception {
    X500Name rootName = new JcaX509CertificateHolder(rootEntry.getCertificate().getCertificate()).getSubject();
    KeyPair childKeyPair = generateKeyPair(algorithm.getEncryptionAlgorithm());

    X500Name childSubject = new X500Name("CN=SignerFake,O=DSS-test");
    CertificateToken child = generateRootCertificateWithCrl(algorithm, childSubject, rootName,
            rootEntry.getPrivateKey(), childKeyPair.getPublic(), notBefore, notAfter);
    CertificateToken[] chain = createChildCertificateChain(rootEntry);

    return new MockPrivateKeyEntry(algorithm.getEncryptionAlgorithm(), child, chain, childKeyPair.getPrivate());
}

From source file:eu.europa.esig.dss.test.gen.CertificateService.java

License:Open Source License

public MockPrivateKeyEntry generateSelfSignedCertificate(final SignatureAlgorithm algorithm, boolean rootCrl)
        throws Exception {
    KeyPair keyPair = generateKeyPair(algorithm.getEncryptionAlgorithm());
    X500Name issuer = new X500Name("CN=RootSelfSignedFake,O=DSS-test");

    Date notBefore = new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000)); // yesterday
    Date notAfter = new Date(System.currentTimeMillis() + (10 * 24 * 60 * 60 * 100000)); // 1000d

    CertificateToken certificate = null;
    if (rootCrl) {
        certificate = generateRootCertificateWithCrl(algorithm, issuer, issuer, keyPair.getPrivate(),
                keyPair.getPublic(), notBefore, notAfter);
    } else {/*from  w  w  w  . j a v a 2s . co  m*/
        certificate = generateRootCertificateWithoutCrl(algorithm, issuer, issuer, keyPair.getPrivate(),
                keyPair.getPublic(), notBefore, notAfter);
    }

    return new MockPrivateKeyEntry(algorithm.getEncryptionAlgorithm(), certificate, keyPair.getPrivate());
}

From source file:eu.europa.esig.dss.test.gen.CertificateService.java

License:Open Source License

public MockPrivateKeyEntry generateTspCertificate(final SignatureAlgorithm algorithm) throws Exception {
    KeyPair keyPair = generateKeyPair(algorithm.getEncryptionAlgorithm());
    X500Name issuer = new X500Name("CN=RootIssuerTSPFake,O=DSS-test");
    X500Name subject = new X500Name("CN=RootSubjectTSP,O=DSS-test");

    final Date notBefore = new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000)); // yesterday
    final Date notAfter = new Date(System.currentTimeMillis() + (10 * 24 * 60 * 60 * 100000)); // 1000d

    // generate certificate
    CertificateToken cert = generateTspCertificate(algorithm, keyPair, issuer, subject, notBefore, notAfter);
    return new MockPrivateKeyEntry(algorithm.getEncryptionAlgorithm(), cert, keyPair.getPrivate());
}

From source file:eu.europa.esig.dss.xades.signature.XAdESBuilder.java

License:Open Source License

/**
 * Incorporates the certificate's references as a child of the given parent node. The first element of the {@code X509Certificate} {@code List} MUST be the signing
 * certificate./*from  w ww  . ja  va 2s .c o m*/
 *
 * @param signingCertificateDom DOM parent element
 * @param certificates          {@code List} of the certificates to be incorporated
 */
protected void incorporateCertificateRef(final Element signingCertificateDom,
        final List<CertificateToken> certificates) {

    for (final CertificateToken certificate : certificates) {

        final Element certDom = DSSXMLUtils.addElement(documentDom, signingCertificateDom, XAdES, XADES_CERT);

        final Element certDigestDom = DSSXMLUtils.addElement(documentDom, certDom, XAdES, XADES_CERT_DIGEST);

        final DigestAlgorithm signingCertificateDigestMethod = params.getSigningCertificateDigestMethod();
        incorporateDigestMethod(certDigestDom, signingCertificateDigestMethod);

        final InMemoryDocument inMemoryCertificate = new InMemoryDocument(certificate.getEncoded());
        incorporateDigestValue(certDigestDom, signingCertificateDigestMethod, inMemoryCertificate);

        if (params.isEn319132()) {
            try {
                final Element issuerSerialDom = DSSXMLUtils.addElement(documentDom, certDom, XAdES,
                        XADES_ISSUER_SERIAL_V2);

                String name = certificate.getCertificate().getIssuerX500Principal().getName();
                IssuerAndSerialNumber issuerAndSerial = new IssuerAndSerialNumber(new X500Name(name),
                        certificate.getCertificate().getSerialNumber());
                byte[] issuer = Base64.encodeBase64(issuerAndSerial.getEncoded());
                DSSXMLUtils.setTextNode(documentDom, issuerSerialDom, new String(issuer));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else {
            final Element issuerSerialDom = DSSXMLUtils.addElement(documentDom, certDom, XAdES,
                    XADES_ISSUER_SERIAL);

            final Element x509IssuerNameDom = DSSXMLUtils.addElement(documentDom, issuerSerialDom, XMLNS,
                    DS_X509_ISSUER_NAME);
            final String issuerX500PrincipalName = certificate.getIssuerX500Principal().getName();
            DSSXMLUtils.setTextNode(documentDom, x509IssuerNameDom, issuerX500PrincipalName);

            final Element x509SerialNumberDom = DSSXMLUtils.addElement(documentDom, issuerSerialDom, XMLNS,
                    DS_X509_SERIAL_NUMBER);
            final BigInteger serialNumber = certificate.getSerialNumber();
            final String serialNumberString = new String(serialNumber.toString());
            DSSXMLUtils.setTextNode(documentDom, x509SerialNumberDom, serialNumberString);
        }
    }
}