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

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

Introduction

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

Prototype

public boolean equals(Object obj) 

Source Link

Document

test for equality - note: case is ignored.

Usage

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

License:EUPL

/**
 * Compares 2 X500Principals to detect if they principalEquals
 *
 * @param principal1// w w w  .  ja v a 2s . c o  m
 * @param principal2
 * @return true if arguments are not null and principalEquals
 */
public static boolean principalNotNullEquals(X500Name principal1, X500Name principal2) {
    if (principal1 == null || principal2 == null) {
        return false;
    }

    return principal1.equals(principal2);
}

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

License:Open Source License

/**
 * checks if the two names are equal via the equals-method
 *
 * @param p1 not null//from  w  w w.  jav  a  2  s .  c o m
 * @param p2 nullable
 * @return true if {@link X500Principal#equals(Object)}
 */
public static boolean viaEquals(final org.bouncycastle.asn1.x500.X500Name p1,
        final org.bouncycastle.asn1.x500.X500Name p2) {
    return p1.equals(p2);
}

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

License:Open Source License

@Override
public X509Certificate getSigningCertificate() {
    try {// w ww.j  a  v  a2  s  . c o  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.ec.markt.dss.validation102853.X500PrincipalMatcher.java

License:Open Source License

/**
 * checks if the two names are equal via the equals-method
 *
 * @param p1 not null/*from  w ww  .j a va 2s .  c o  m*/
 * @param p2 nullable
 * @return true if {@link javax.security.auth.x500.X500Principal#equals(Object)}
 */
public static boolean viaEquals(final X500Name p1, final X500Name p2) {
    return p1.equals(p2);
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

License:Open Source License

private boolean hasMatchingName(X500Name name, GeneralName[] generalNames) {
    if (name == null || generalNames == null) {
        return false;
    }/*  w w w  . j  a v a  2s.c o m*/

    for (GeneralName generalName : generalNames) {
        /* 
         * we only need to compare directoryNames
         */
        if (generalName.getTagNo() == GeneralName.directoryName) {
            if (name.equals(X500Name.getInstance(generalName.getName()))) {
                return true;
            }
        }
    }

    return false;
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

License:Open Source License

private boolean hasMatchingName(DistributionPointName dpn1, DistributionPointName dpn2, X500Principal issuer)
        throws IOException {
    if (dpn1 == null && dpn2 == null) {
        return true;
    }//from ww  w.  jav  a 2s .  c o m

    if (dpn1 == null || dpn2 == null) {
        return false;
    }

    GeneralName[] generalNames1 = null;
    GeneralName[] generalNames2 = null;

    X500Name name1 = null;
    X500Name name2 = null;

    if (dpn1.getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) {
        name1 = getFullName(issuer, dpn1);
    } else {
        generalNames1 = GeneralNames.getInstance(dpn1.getName()).getNames();
    }

    if (dpn2.getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) {
        name2 = getFullName(issuer, dpn2);
    } else {
        generalNames2 = GeneralNames.getInstance(dpn2.getName()).getNames();
    }

    if (generalNames1 != null && generalNames2 != null) {
        return CollectionUtils.containsAny(Arrays.asList(generalNames1), Arrays.asList(generalNames2));
    }

    if (name1 != null && name2 != null) {
        return name1.equals(name2);
    }

    return name1 != null ? hasMatchingName(name1, generalNames2) : hasMatchingName(name2, generalNames1);
}

From source file:org.apache.jmeter.assertions.SMIMEAssertion.java

License:Apache License

private static AssertionResult verifySignature(SMIMEAssertionTestElement testElement, SMIMESignedParser s,
        String name) throws CMSException {
    AssertionResult res = new AssertionResult(name);

    try {//from  w ww  . j  a v  a2s  . com
        Store certs = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Iterator<?> signerIt = signers.getSigners().iterator();

        if (signerIt.hasNext()) {

            SignerInformation signer = (SignerInformation) signerIt.next();
            Iterator<?> certIt = certs.getMatches(signer.getSID()).iterator();

            if (certIt.hasNext()) {
                // the signer certificate
                X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

                if (testElement.isVerifySignature()) {

                    SignerInformationVerifier verifier = null;
                    try {
                        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert);
                    } catch (OperatorCreationException e) {
                        log.error("Can't create a provider", e);
                    }
                    if (verifier == null || !signer.verify(verifier)) {
                        res.setFailure(true);
                        res.setFailureMessage("Signature is invalid");
                    }
                }

                if (testElement.isSignerCheckConstraints()) {
                    StringBuilder failureMessage = new StringBuilder();

                    String serial = testElement.getSignerSerial();
                    if (!JOrphanUtils.isBlank(serial)) {
                        BigInteger serialNbr = readSerialNumber(serial);
                        if (!serialNbr.equals(cert.getSerialNumber())) {
                            res.setFailure(true);
                            failureMessage.append("Serial number ").append(serialNbr)
                                    .append(" does not match serial from signer certificate: ")
                                    .append(cert.getSerialNumber()).append("\n");
                        }
                    }

                    String email = testElement.getSignerEmail();
                    if (!JOrphanUtils.isBlank(email)) {
                        List<String> emailFromCert = getEmailFromCert(cert);
                        if (!emailFromCert.contains(email)) {
                            res.setFailure(true);
                            failureMessage.append("Email address \"").append(email)
                                    .append("\" not present in signer certificate\n");
                        }

                    }

                    String subject = testElement.getSignerDn();
                    if (subject.length() > 0) {
                        final X500Name certPrincipal = cert.getSubject();
                        log.debug("DN from cert: " + certPrincipal.toString());
                        X500Name principal = new X500Name(subject);
                        log.debug("DN from assertion: " + principal.toString());
                        if (!principal.equals(certPrincipal)) {
                            res.setFailure(true);
                            failureMessage.append("Distinguished name of signer certificate does not match \"")
                                    .append(subject).append("\"\n");
                        }
                    }

                    String issuer = testElement.getIssuerDn();
                    if (issuer.length() > 0) {
                        final X500Name issuerX500Name = cert.getIssuer();
                        log.debug("IssuerDN from cert: " + issuerX500Name.toString());
                        X500Name principal = new X500Name(issuer);
                        log.debug("IssuerDN from assertion: " + principal);
                        if (!principal.equals(issuerX500Name)) {
                            res.setFailure(true);
                            failureMessage
                                    .append("Issuer distinguished name of signer certificate does not match \"")
                                    .append(subject).append("\"\n");
                        }
                    }

                    if (failureMessage.length() > 0) {
                        res.setFailureMessage(failureMessage.toString());
                    }
                }

                if (testElement.isSignerCheckByFile()) {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    X509CertificateHolder certFromFile;
                    InputStream inStream = null;
                    try {
                        inStream = new BufferedInputStream(
                                new FileInputStream(testElement.getSignerCertFile()));
                        certFromFile = new JcaX509CertificateHolder(
                                (X509Certificate) cf.generateCertificate(inStream));
                    } finally {
                        IOUtils.closeQuietly(inStream);
                    }

                    if (!certFromFile.equals(cert)) {
                        res.setFailure(true);
                        res.setFailureMessage("Signer certificate does not match certificate "
                                + testElement.getSignerCertFile());
                    }
                }

            } else {
                res.setFailure(true);
                res.setFailureMessage("No signer certificate found in signature");
            }

        }

        // TODO support multiple signers
        if (signerIt.hasNext()) {
            log.warn("SMIME message contains multiple signers! Checking multiple signers is not supported.");
        }

    } catch (GeneralSecurityException e) {
        log.error(e.getMessage(), e);
        res.setError(true);
        res.setFailureMessage(e.getMessage());
    } catch (FileNotFoundException e) {
        res.setFailure(true);
        res.setFailureMessage("certificate file not found: " + e.getMessage());
    }

    return res;
}

From source file:org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService.java

License:Apache License

@SuppressWarnings("unchecked")
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = CryptoFunctions.getMessageDigest(signatureConfig.getTspDigestAlgo());
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);/*from   w w  w.  j a v  a2 s.c o  m*/
    String requestPolicy = signatureConfig.getTspRequestPolicy();
    if (requestPolicy != null) {
        requestGenerator.setReqPolicy(new ASN1ObjectIdentifier(requestPolicy));
    }
    ASN1ObjectIdentifier digestAlgoOid = mapDigestAlgoToOID(signatureConfig.getTspDigestAlgo());
    TimeStampRequest request = requestGenerator.generate(digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP POST request
    Proxy proxy = Proxy.NO_PROXY;
    if (signatureConfig.getProxyUrl() != null) {
        URL proxyUrl = new URL(signatureConfig.getProxyUrl());
        String host = proxyUrl.getHost();
        int port = proxyUrl.getPort();
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, (port == -1 ? 80 : port)));
    }

    HttpURLConnection huc = (HttpURLConnection) new URL(signatureConfig.getTspUrl()).openConnection(proxy);

    if (signatureConfig.getTspUser() != null) {
        String userPassword = signatureConfig.getTspUser() + ":" + signatureConfig.getTspPass();
        String encoding = DatatypeConverter
                .printBase64Binary(userPassword.getBytes(Charset.forName("iso-8859-1")));
        huc.setRequestProperty("Authorization", "Basic " + encoding);
    }

    huc.setRequestMethod("POST");
    huc.setConnectTimeout(20000);
    huc.setReadTimeout(20000);
    huc.setDoOutput(true); // also sets method to POST.
    huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent());
    huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() ? "application/timestamp-request"
            : "application/timestamp-query"); // "; charset=ISO-8859-1");

    OutputStream hucOut = huc.getOutputStream();
    hucOut.write(encodedRequest);

    // invoke TSP service
    huc.connect();

    int statusCode = huc.getResponseCode();
    if (statusCode != 200) {
        LOG.log(POILogger.ERROR, "Error contacting TSP server ", signatureConfig.getTspUrl());
        throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl());
    }

    // HTTP input validation
    String contentType = huc.getHeaderField("Content-Type");
    if (null == contentType) {
        throw new RuntimeException("missing Content-Type header");
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(huc.getInputStream(), bos);
    LOG.log(POILogger.DEBUG, "response content: ", bos.toString());

    if (!contentType.startsWith(signatureConfig.isTspOldProtocol() ? "application/timestamp-response"
            : "application/timestamp-reply")) {
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }

    if (bos.size() == 0) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    TimeStampResponse timeStampResponse = new TimeStampResponse(bos.toByteArray());
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.log(POILogger.DEBUG, "status: " + timeStampResponse.getStatus());
        LOG.log(POILogger.DEBUG, "status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.log(POILogger.DEBUG, "fail info int value: " + failInfo.intValue());
            if (/*PKIFailureInfo.unacceptedPolicy*/(1 << 8) == failInfo.intValue()) {
                LOG.log(POILogger.DEBUG, "unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Name signerCertIssuer = signerId.getIssuer();
    LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber);
    LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    Collection<X509CertificateHolder> certificates = timeStampToken.getCertificates().getMatches(null);

    X509CertificateHolder signerCert = null;
    Map<X500Name, X509CertificateHolder> certificateMap = new HashMap<X500Name, X509CertificateHolder>();
    for (X509CertificateHolder certificate : certificates) {
        if (signerCertIssuer.equals(certificate.getIssuer())
                && signerCertSerialNumber.equals(certificate.getSerialNumber())) {
            signerCert = certificate;
        }
        certificateMap.put(certificate.getSubject(), certificate);
    }

    // TSP signer cert path building
    if (signerCert == null) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new ArrayList<X509Certificate>();
    JcaX509CertificateConverter x509converter = new JcaX509CertificateConverter();
    x509converter.setProvider("BC");
    X509CertificateHolder certificate = signerCert;
    do {
        LOG.log(POILogger.DEBUG, "adding to certificate chain: " + certificate.getSubject());
        tspCertificateChain.add(x509converter.getCertificate(certificate));
        if (certificate.getSubject().equals(certificate.getIssuer())) {
            break;
        }
        certificate = certificateMap.get(certificate.getIssuer());
    } while (null != certificate);

    // verify TSP signer signature
    X509CertificateHolder holder = new X509CertificateHolder(tspCertificateChain.get(0).getEncoded());
    DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator();
    DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder();
    DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder();
    BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider();
    BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder,
            hashAlgoFinder, calculator);
    SignerInformationVerifier verifier = verifierBuilder.build(holder);

    timeStampToken.validate(verifier);

    // verify TSP signer certificate
    if (signatureConfig.getTspValidator() != null) {
        signatureConfig.getTspValidator().validate(tspCertificateChain, revocationData);
    }

    LOG.log(POILogger.DEBUG, "time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Checks that the given SubjectDN / SAN satisfies the Name Constraints of the given issuer (if there are any).
 * This method checks the Name Constraints in the given issuer only. A complete implementation of
 * name constraints should check the whole certificate chain.
 * //from ww w.  j a v a 2 s  .co m
 * @param issuer Issuing CA.
 * @param subjectDNName Subject DN to check. Optional.
 * @param subjectAltName Subject Alternative Name to check. Optional.
 * @throws CertificateExtensionException
 */
public static void checkNameConstraints(X509Certificate issuer, X500Name subjectDNName,
        GeneralNames subjectAltName) throws IllegalNameException {
    final byte[] ncbytes = issuer.getExtensionValue(Extension.nameConstraints.getId());
    final ASN1OctetString ncstr = (ncbytes != null ? DEROctetString.getInstance(ncbytes) : null);
    final ASN1Sequence ncseq = (ncbytes != null ? DERSequence.getInstance(ncstr.getOctets()) : null);
    final NameConstraints nc = (ncseq != null ? NameConstraints.getInstance(ncseq) : null);

    if (nc != null) {
        if (subjectDNName != null) {
            // Skip check for root CAs
            final X500Name issuerDNName = X500Name.getInstance(issuer.getSubjectX500Principal().getEncoded());
            if (issuerDNName.equals(subjectDNName)) {
                return;
            }
        }

        final PKIXNameConstraintValidator validator = new PKIXNameConstraintValidator();

        GeneralSubtree[] permitted = nc.getPermittedSubtrees();
        GeneralSubtree[] excluded = nc.getExcludedSubtrees();

        if (permitted != null) {
            validator.intersectPermittedSubtree(permitted);
        }
        if (excluded != null) {
            for (GeneralSubtree subtree : excluded) {
                validator.addExcludedSubtree(subtree);
            }
        }

        if (subjectDNName != null) {
            GeneralName dngn = new GeneralName(subjectDNName);
            try {
                validator.checkPermitted(dngn);
                validator.checkExcluded(dngn);
            } catch (PKIXNameConstraintValidatorException e) {
                final String dnStr = subjectDNName.toString();
                final boolean isLdapOrder = dnHasMultipleComponents(dnStr) && !isDNReversed(dnStr);
                if (isLdapOrder) {
                    final String msg = intres.getLocalizedMessage("nameconstraints.x500dnorderrequired");
                    throw new IllegalNameException(msg);
                } else {
                    final String msg = intres.getLocalizedMessage("nameconstraints.forbiddensubjectdn",
                            subjectDNName);
                    throw new IllegalNameException(msg, e);
                }
            }
        }

        if (subjectAltName != null) {
            for (GeneralName sangn : subjectAltName.getNames()) {
                try {
                    validator.checkPermitted(sangn);
                    validator.checkExcluded(sangn);
                } catch (PKIXNameConstraintValidatorException e) {
                    final String msg = intres.getLocalizedMessage("nameconstraints.forbiddensubjectaltname",
                            sangn);
                    throw new IllegalNameException(msg, e);
                }
            }
        }
    }
}

From source file:org.codice.ddf.security.ocsp.checker.OcspChecker.java

License:Open Source License

/**
 * Returns an {@link X509CertificateHolder} containing the issuer of the given {@param name}.
 * Search is performed in the given {@param truststore}.
 *
 * @param name - the {@link X500Name} of the issuer.
 * @param truststore - the {@link KeyStore} to check.
 * @return {@link X509CertificateHolder} of the certificate with the given {@param name}.
 * @throws OcspCheckerException if the {@param name} cannot be found in the {@param truststore}.
 */// w  ww  .  j  a va2 s .  c  o  m
private X509CertificateHolder getCertFromTruststoreWithX500Name(X500Name name, KeyStore truststore)
        throws OcspCheckerException {
    Enumeration<String> aliases;

    try {
        aliases = truststore.aliases();
    } catch (KeyStoreException e) {
        throw new OcspCheckerException("Problem getting aliases from truststore." + NOT_VERIFIED_MSG, e);
    }

    while (aliases.hasMoreElements()) {
        String currentAlias = aliases.nextElement();

        try {
            java.security.cert.Certificate currentCert = truststore.getCertificate(currentAlias);
            X509CertificateHolder currentCertHolder = new X509CertificateHolder(currentCert.getEncoded());
            X500Name currentName = currentCertHolder.getSubject();
            if (name.equals(currentName)) {
                return currentCertHolder;
            }
        } catch (CertificateEncodingException | IOException | KeyStoreException e) {
            LOGGER.debug("Problem loading truststore certificate." + CONTINUING_MSG, e);
        }
    }

    throw new OcspCheckerException(
            String.format("Could not find cert matching X500Name of %s.", name) + NOT_VERIFIED_MSG);
}