Example usage for javax.security.auth.x500 X500Principal CANONICAL

List of usage examples for javax.security.auth.x500 X500Principal CANONICAL

Introduction

In this page you can find the example usage for javax.security.auth.x500 X500Principal CANONICAL.

Prototype

String CANONICAL

To view the source code for javax.security.auth.x500 X500Principal CANONICAL.

Click Source Link

Document

Canonical String format of Distinguished Names.

Usage

From source file:org.tigase.mobile.TrustCertDialog.java

public static Dialog createDIalogInstance(final Context context, final String account,
        final DataCertificateException cause, final Resources res, final Runnable actionAfterOK) {
    final X509Certificate[] chain = cause.getChain();

    final StringBuilder chainInfo = new StringBuilder();
    MessageDigest sha1 = null;//from  w  w w  .  ja  va2 s.  co m

    try {
        sha1 = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
    }

    for (int i = 0; i < chain.length; i++) {
        chainInfo.append(res.getString(R.string.trustcert_certchain, i)).append("\n");
        chainInfo
                .append(res.getString(R.string.trustcert_subject,
                        chain[i].getSubjectX500Principal().getName(X500Principal.CANONICAL).toString()))
                .append("\n");
        chainInfo
                .append(res.getString(R.string.trustcert_issuer,
                        chain[i].getIssuerX500Principal().getName(X500Principal.CANONICAL).toString()))
                .append("\n");

        if (sha1 != null) {
            sha1.reset();
            try {
                char[] sha1sum = encodeHex(sha1.digest(chain[i].getEncoded()));
                chainInfo.append(res.getString(R.string.trustcert_fingerprint, new String(sha1sum)))
                        .append("\n");
            } catch (CertificateEncodingException e) {
            }
        }
    }

    Builder builder = new AlertDialog.Builder(context);
    builder.setIcon(android.R.drawable.ic_dialog_alert);
    builder.setTitle(R.string.trustcert_dialog_title);

    builder.setMessage(res.getString(R.string.trustcert_question, chainInfo));

    builder.setCancelable(true);
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int whichButton) {
            SecureTrustManagerFactory.add(chain);
            if (actionAfterOK != null)
                actionAfterOK.run();
        }
    });
    builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.dismiss();
        }
    });

    return builder.create();
}

From source file:eu.europa.esig.dss.x509.CertificatePool.java

/**
 * This method returns the instance of a {@link CertificateToken} corresponding to the given {@link X509Certificate}.
 * If the given certificate is not yet present in the pool it will added. If the {@link CertificateToken} exists
 * already in the pool but has no {@link ServiceInfo} this reference will be added.
 *
 * @param certificateToAdd/*www  . jav a 2 s .  c  o  m*/
 * @param sources
 * @param services
 * @return
 */
public CertificateToken getInstance(final CertificateToken certificateToAdd,
        final Set<CertificateSourceType> sources, final Set<ServiceInfo> services) {

    if (certificateToAdd == null) {
        throw new NullPointerException("The certificate must be filled");
    }

    if (CollectionUtils.isEmpty(sources)) {
        throw new IllegalStateException("The certificate source type must be set.");
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Certificate to add: " + certificateToAdd.getIssuerX500Principal() + "|"
                + certificateToAdd.getSerialNumber());
    }

    final TokenIdentifier id = certificateToAdd.getDSSId();
    synchronized (certById) {

        CertificateToken certToken = certById.get(id);
        if (certToken == null) {

            LOG.debug("Certificate " + id + " is not in the pool");
            certToken = certificateToAdd;
            certById.put(id, certToken);
            final String subjectName = certificateToAdd.getSubjectX500Principal()
                    .getName(X500Principal.CANONICAL);
            List<CertificateToken> list = certBySubject.get(subjectName);
            if (list == null) {

                list = new ArrayList<CertificateToken>();
                certBySubject.put(subjectName, list);
            }
            list.add(certToken);
        } else {

            LOG.debug("Certificate " + id + " is already in the pool");
            final X509Certificate foundCertificate = certToken.getCertificate();
            final byte[] foundCertificateSignature = foundCertificate.getSignature();
            final byte[] certificateToAddSignature = certificateToAdd.getSignature();
            if (!Arrays.equals(foundCertificateSignature, certificateToAddSignature)) {

                LOG.warn(" Found certificate: " + certToken.getIssuerX500Principal().toString() + "|"
                        + certToken.getSerialNumber());
                LOG.warn(
                        "More than one certificate for the same issuer subject name and serial number! The standard is not met by the certificate issuer!");
            }
        }
        for (final CertificateSourceType sourceType : sources) {
            certToken.addSourceType(sourceType);
        }
        if (services != null) {
            for (final ServiceInfo serviceInfo : services) {
                certToken.addServiceInfo(serviceInfo);
            }
        }
        return certToken;
    }
}

From source file:mitm.common.security.certificate.X500PrincipalInspector.java

/**
 * Returns the Canonical String version of the X500Principal
 *///from  w  w  w . j a  v a2 s.  com
public static String getCanonical(X500Principal principal) {
    if (principal == null) {
        return null;
    }

    return principal.getName(X500Principal.CANONICAL);
}

From source file:eu.europa.esig.dss.x509.CertificatePool.java

/**
 * This method returns the list of certificates with the same issuerDN.
 *
 * @param x500Principal subject distinguished name to match.
 * @return If no match is found then an empty list is returned.
 */// ww w  .ja v a  2 s .c om
public List<CertificateToken> get(final X500Principal x500Principal) {

    List<CertificateToken> certificateTokenList = null;
    if (x500Principal != null) {

        /**
         * TODO: (Bob: 2014 Feb 21) For some certificates the comparison based on X500Principal.CANONICAL does not returns the same result as this based on X500Principal
         * .RFC2253. The CANONICAL form seems to be compliant with the requirements of RFC 2459.
         * The returned list can be maybe enriched by RFC2253 form?
         */
        final String x500PrincipalCanonicalized = x500Principal.getName(X500Principal.CANONICAL);
        certificateTokenList = certBySubject.get(x500PrincipalCanonicalized);
    }
    if (certificateTokenList == null) {

        certificateTokenList = new ArrayList<CertificateToken>();
    }
    return Collections.unmodifiableList(certificateTokenList);
}

From source file:eu.europa.esig.dss.x509.CertificateToken.java

/**
 * Checks if the certificate is self-signed.
 *
 * @return//from w w w .  j a  v a 2s  .c  o m
 */
@Override
public boolean isSelfSigned() {

    if (selfSigned == null) {

        final String n1 = x509Certificate.getSubjectX500Principal().getName(X500Principal.CANONICAL);
        final String n2 = x509Certificate.getIssuerX500Principal().getName(X500Principal.CANONICAL);
        selfSigned = n1.equals(n2);
    }
    return selfSigned;
}

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

@Override
public void checkSigningCertificate() {

    final CandidatesForSigningCertificate candidates = getCandidatesForSigningCertificate();
    /**//from w  w w  .  j  a v  a2 s .c  om
     * The ../SignedProperties/SignedSignatureProperties/SigningCertificate element MAY contain references and digests values of other
     * certificates (that MAY form a chain up to the point of trust).
     */
    boolean isEn319132 = false;
    NodeList list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT);
    int length = list.getLength();
    if (length == 0) {
        list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT_V2);
        length = list.getLength();
        isEn319132 = true;
    }
    if (length == 0) {
        final CertificateValidity theCertificateValidity = candidates.getTheCertificateValidity();
        final CertificateToken certificateToken = theCertificateValidity == null ? null
                : theCertificateValidity.getCertificateToken();
        // The check need to be done at the level of KeyInfo
        for (final Reference reference : references) {

            final String uri = reference.getURI();
            if (!uri.startsWith("#")) {
                continue;
            }

            final String id = uri.substring(1);
            final Element element = signatureElement.getOwnerDocument().getElementById(id);
            // final Element element =
            // DSSXMLUtils.getElement(signatureElement, "");
            if (!hasSignatureAsParent(element)) {

                continue;
            }
            if ((certificateToken != null) && id.equals(certificateToken.getXmlId())) {

                theCertificateValidity.setSigned(element.getNodeName());
                return;
            }
        }
    }
    // This Map contains the list of the references to the certificate which
    // were already checked and which correspond to a certificate.
    Map<Element, Boolean> alreadyProcessedElements = new HashMap<Element, Boolean>();

    final List<CertificateValidity> certificateValidityList = candidates.getCertificateValidityList();
    for (final CertificateValidity certificateValidity : certificateValidityList) {

        final CertificateToken certificateToken = certificateValidity.getCertificateToken();
        for (int ii = 0; ii < length; ii++) {

            certificateValidity.setAttributePresent(true);
            final Element element = (Element) list.item(ii);
            if (alreadyProcessedElements.containsKey(element)) {
                continue;
            }
            final Element certDigestElement = DSSXMLUtils.getElement(element,
                    xPathQueryHolder.XPATH__CERT_DIGEST);
            certificateValidity.setDigestPresent(certDigestElement != null);

            final Element digestMethodElement = DSSXMLUtils.getElement(certDigestElement,
                    xPathQueryHolder.XPATH__DIGEST_METHOD);
            if (digestMethodElement == null) {
                continue;
            }
            final String xmlAlgorithmName = digestMethodElement.getAttribute(XMLE_ALGORITHM);
            // The default algorithm is used in case of bad encoded
            // algorithm name
            final DigestAlgorithm digestAlgorithm = DigestAlgorithm.forXML(xmlAlgorithmName,
                    DigestAlgorithm.SHA1);

            final Element digestValueElement = DSSXMLUtils.getElement(element,
                    xPathQueryHolder.XPATH__CERT_DIGEST_DIGEST_VALUE);
            if (digestValueElement == null) {
                continue;
            }
            // That must be a binary comparison
            final byte[] storedBase64DigestValue = DSSUtils
                    .base64StringToBase64Binary(digestValueElement.getTextContent());

            /**
             * Step 1:<br>
             * Take the first child of the property and check that the content of ds:DigestValue matches the result of digesting <i>the candidate
             * for</i> the signing certificate with the algorithm indicated in ds:DigestMethod. If they do not match, take the next child and
             * repeat this step until a matching child element has been found or all children of the element have been checked. If they do match,
             * continue with step 2. If the last element is reached without finding any match, the validation of this property shall be taken as
             * failed and INVALID/FORMAT_FAILURE is returned.
             */
            final byte[] digest = DSSUtils.digest(digestAlgorithm, certificateToken.getEncoded());
            final byte[] recalculatedBase64DigestValue = Base64.encodeBase64(digest);
            certificateValidity.setDigestEqual(false);
            BigInteger serialNumber = new BigInteger("0");
            if (Arrays.equals(recalculatedBase64DigestValue, storedBase64DigestValue)) {
                X500Principal issuerName = null;
                if (isEn319132) {
                    final Element issuerNameEl = DSSXMLUtils.getElement(element,
                            xPathQueryHolder.XPATH__X509_ISSUER_V2);
                    if (issuerNameEl != null) {
                        final String textContent = issuerNameEl.getTextContent();
                        ASN1InputStream is = new ASN1InputStream(Base64.decodeBase64(textContent));
                        ASN1Sequence seq = null;
                        try {
                            seq = (ASN1Sequence) is.readObject();
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //IssuerAndSerialNumber issuerAndSerial = new IssuerAndSerialNumber(seq);
                        IssuerAndSerialNumber issuerAndSerial = IssuerAndSerialNumber.getInstance(seq);
                        issuerName = new X500Principal(issuerAndSerial.getName().toString());
                        serialNumber = issuerAndSerial.getSerialNumber().getValue();
                    }
                } else {
                    final Element issuerNameEl = DSSXMLUtils.getElement(element,
                            xPathQueryHolder.XPATH__X509_ISSUER_NAME);
                    // This can be allayed when the distinguished name is not
                    // correctly encoded
                    // final String textContent =
                    // DSSUtils.unescapeMultiByteUtf8Literals(issuerNameEl.getTextContent());
                    final String textContent = issuerNameEl.getTextContent();

                    issuerName = DSSUtils.getX500PrincipalOrNull(textContent);
                }
                final X500Principal candidateIssuerName = certificateToken.getIssuerX500Principal();

                // final boolean issuerNameMatches =
                // candidateIssuerName.equals(issuerName);
                final boolean issuerNameMatches = DSSUtils.x500PrincipalAreEquals(candidateIssuerName,
                        issuerName);
                if (!issuerNameMatches) {

                    final String c14nCandidateIssuerName = candidateIssuerName.getName(X500Principal.CANONICAL);
                    LOG.info("candidateIssuerName: " + c14nCandidateIssuerName);
                    final String c14nIssuerName = issuerName == null ? ""
                            : issuerName.getName(X500Principal.CANONICAL);
                    LOG.info("issuerName         : " + c14nIssuerName);
                }

                if (!isEn319132) {
                    final Element serialNumberEl = DSSXMLUtils.getElement(element,
                            xPathQueryHolder.XPATH__X509_SERIAL_NUMBER);
                    final String serialNumberText = serialNumberEl.getTextContent();
                    // serial number can contain leading and trailing whitespace.
                    serialNumber = new BigInteger(serialNumberText.trim());
                }
                final BigInteger candidateSerialNumber = certificateToken.getSerialNumber();
                final boolean serialNumberMatches = candidateSerialNumber.equals(serialNumber);

                certificateValidity.setDigestEqual(true);
                certificateValidity.setSerialNumberEqual(serialNumberMatches);
                certificateValidity.setDistinguishedNameEqual(issuerNameMatches);
                // The certificate was identified
                alreadyProcessedElements.put(element, true);
                // If the signing certificate is not set yet then it must be
                // done now. Actually if the signature is tempered then the
                // method checkSignatureIntegrity cannot set the signing
                // certificate.
                if (candidates.getTheCertificateValidity() == null) {

                    candidates.setTheCertificateValidity(certificateValidity);
                }
                break;
            }
        }
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.SignedDocumentValidator.java

/**
 * This method deals with the certificate's details. The retrieved information is transformed to the JAXB object.
 *
 * @param certToken//from w w w  . j  a  v a 2s  .  c o m
 * @return
 */
private XmlCertificate dealCertificateDetails(final Set<DigestAlgorithm> usedCertificatsDigestAlgorithms,
        final CertificateToken certToken) {

    final XmlCertificate xmlCert = DIAGNOSTIC_DATA_OBJECT_FACTORY.createXmlCertificate();

    xmlCert.setId(certToken.getDSSId());
    final XmlSubjectDistinguishedName xmlSubject = DIAGNOSTIC_DATA_OBJECT_FACTORY
            .createXmlSubjectDistinguishedName();
    xmlSubject.setFormat(X500Principal.CANONICAL);
    xmlSubject.setValue(certToken.getSubjectX500Principal().getName(X500Principal.CANONICAL));
    xmlCert.setSubjectDistinguishedName(xmlSubject);

    final XmlIssuerDistinguishedName xmlIssuer = DIAGNOSTIC_DATA_OBJECT_FACTORY
            .createXmlIssuerDistinguishedName();
    xmlIssuer.setFormat(X500Principal.CANONICAL);
    xmlIssuer.setValue(certToken.getIssuerX500Principal().getName(X500Principal.CANONICAL));
    xmlCert.setIssuerDistinguishedName(xmlIssuer);
    xmlCert.setSerialNumber(certToken.getSerialNumber());

    for (final DigestAlgorithm digestAlgorithm : usedCertificatsDigestAlgorithms) {

        final XmlDigestAlgAndValueType xmlDigestAlgAndValue = new XmlDigestAlgAndValueType();
        xmlDigestAlgAndValue.setDigestMethod(digestAlgorithm.getName());
        xmlDigestAlgAndValue.setDigestValue(certToken.getDigestValue(digestAlgorithm));
        xmlCert.getDigestAlgAndValue().add(xmlDigestAlgAndValue);
    }
    xmlCert.setIssuerCertificate(certToken.getIssuerTokenDSSId());
    xmlCert.setNotAfter(DSSUtils.createXMGregorianCalendar(certToken.getNotAfter()));
    xmlCert.setNotBefore(DSSUtils.createXMGregorianCalendar(certToken.getNotBefore()));
    final PublicKey publicKey = certToken.getPublicKey();
    xmlCert.setPublicKeySize(PublicKeyUtils.getPublicKeySize(publicKey));
    xmlCert.setPublicKeyEncryptionAlgo(PublicKeyUtils.getPublicKeyEncryptionAlgo(publicKey));
    xmlCert.setAlgoUsedToSignThisToken(certToken.getSignatureAlgo());
    final String signatureAlgoOID = certToken.getSignatureAlgoOID();
    xmlCert.setAlgoOIDUsedToSignThisToken(signatureAlgoOID);
    final SignatureAlgorithm signatureAlgo = SignatureAlgorithm.forOID(signatureAlgoOID);
    xmlCert.setDigestAlgoUsedToSignThisToken(signatureAlgo.getDigestAlgo().getName());
    xmlCert.setEncryptionAlgoUsedToSignThisToken(signatureAlgo.getEncryptionAlgo().getName());
    final String keyLength = getSigningKeyLength((Token) certToken);
    xmlCert.setKeyLengthUsedToSignThisToken(keyLength);
    xmlCert.setSelfSigned(certToken.isSelfSigned());
    xmlCert.setTrusted(certToken.isTrusted());
    xmlCert.setTokenSignatureIntact(certToken.isSignatureIntact());

    return xmlCert;
}

From source file:eu.europa.esig.dss.validation.SignedDocumentValidator.java

/**
 * This method deals with the certificate's details. The retrieved information is transformed to the JAXB object.
 *
 * @param usedDigestAlgorithms//from   w w  w . ja  va2s.  c o  m
 *            set of different digest algorithms used to compute certificate digest
 * @param certToken
 *            current certificate token
 * @return
 */
private XmlCertificate dealCertificateDetails(final Set<DigestAlgorithm> usedDigestAlgorithms,
        final CertificateToken certToken) {

    final XmlCertificate xmlCert = DIAGNOSTIC_DATA_OBJECT_FACTORY.createXmlCertificate();

    xmlCert.setId(certToken.getDSSId().asXmlId());

    XmlDistinguishedName xmlDistinguishedName = xmlForDistinguishedName(X500Principal.CANONICAL,
            certToken.getSubjectX500Principal());
    xmlCert.getSubjectDistinguishedName().add(xmlDistinguishedName);
    xmlDistinguishedName = xmlForDistinguishedName(X500Principal.RFC2253, certToken.getSubjectX500Principal());
    xmlCert.getSubjectDistinguishedName().add(xmlDistinguishedName);

    xmlDistinguishedName = xmlForDistinguishedName(X500Principal.CANONICAL, certToken.getIssuerX500Principal());
    xmlCert.getIssuerDistinguishedName().add(xmlDistinguishedName);
    xmlDistinguishedName = xmlForDistinguishedName(X500Principal.RFC2253, certToken.getIssuerX500Principal());
    xmlCert.getIssuerDistinguishedName().add(xmlDistinguishedName);

    xmlCert.setSerialNumber(certToken.getSerialNumber());

    for (final DigestAlgorithm digestAlgorithm : usedDigestAlgorithms) {

        final XmlDigestAlgAndValueType xmlDigestAlgAndValue = new XmlDigestAlgAndValueType();
        xmlDigestAlgAndValue.setDigestMethod(digestAlgorithm.getName());
        xmlDigestAlgAndValue.setDigestValue(DSSUtils.digest(digestAlgorithm, certToken));
        xmlCert.getDigestAlgAndValue().add(xmlDigestAlgAndValue);
    }
    TokenIdentifier issuerTokenDSSId = certToken.getIssuerTokenDSSId();
    if (issuerTokenDSSId != null) {
        xmlCert.setIssuerCertificate(issuerTokenDSSId.asXmlId());
    }
    xmlCert.setNotAfter(DSSXMLUtils.createXMLGregorianCalendar(certToken.getNotAfter()));
    xmlCert.setNotBefore(DSSXMLUtils.createXMLGregorianCalendar(certToken.getNotBefore()));
    final PublicKey publicKey = certToken.getPublicKey();
    xmlCert.setPublicKeySize(DSSPKUtils.getPublicKeySize(publicKey));
    xmlCert.setPublicKeyEncryptionAlgo(DSSPKUtils.getPublicKeyEncryptionAlgo(publicKey));

    xmlForKeyUsageBits(certToken, xmlCert);

    if (DSSASN1Utils.isOCSPSigning(certToken)) {
        xmlCert.setIdKpOCSPSigning(true);
    }
    if (DSSASN1Utils.hasIdPkixOcspNoCheckExtension(certToken)) {
        xmlCert.setIdPkixOcspNoCheck(true);
    }
    if (DSSASN1Utils.hasExpiredCertOnCRLExtension(certToken)) {
        xmlCert.setExpiredCertOnCRL(true);
    }

    final XmlBasicSignatureType xmlBasicSignatureType = DIAGNOSTIC_DATA_OBJECT_FACTORY
            .createXmlBasicSignatureType();

    final SignatureAlgorithm signatureAlgorithm = certToken.getSignatureAlgorithm();
    xmlBasicSignatureType.setDigestAlgoUsedToSignThisToken(signatureAlgorithm.getDigestAlgorithm().getName());
    xmlBasicSignatureType
            .setEncryptionAlgoUsedToSignThisToken(signatureAlgorithm.getEncryptionAlgorithm().getName());
    final String keyLength = DSSPKUtils.getPublicKeySize(certToken);
    xmlBasicSignatureType.setKeyLengthUsedToSignThisToken(keyLength);
    final boolean signatureIntact = certToken.isSignatureValid();
    xmlBasicSignatureType.setReferenceDataFound(signatureIntact);
    xmlBasicSignatureType.setReferenceDataIntact(signatureIntact);
    xmlBasicSignatureType.setSignatureIntact(signatureIntact);
    xmlBasicSignatureType.setSignatureValid(signatureIntact);
    xmlCert.setBasicSignature(xmlBasicSignatureType);

    final CertificateToken issuerToken = certToken.getIssuerToken();
    final XmlSigningCertificateType xmlSigningCertificate = xmlForSigningCertificate(issuerToken);
    xmlCert.setSigningCertificate(xmlSigningCertificate);

    final XmlCertificateChainType xmlCertChainType = xmlForCertificateChain(issuerToken);
    xmlCert.setCertificateChain(xmlCertChainType);

    xmlCert.setSelfSigned(certToken.isSelfSigned());
    xmlCert.setTrusted(certToken.isTrusted());

    return xmlCert;
}