Example usage for java.security.cert X509Certificate getSubjectX500Principal

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

Introduction

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

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

Returns the subject (subject distinguished name) value from the certificate as an X500Principal .

Usage

From source file:eu.europa.ec.markt.tlmanager.core.validation.Validation.java

/**
 * 5.5.3 Service digital identity//from w ww. jav  a 2s  .com
 * <p/>
 * The TLSO may list more than one certificate to represent the
 * public key, but only when all those certificates relate to the same public key and have identical
 * subject names
 */
void checkRuleAllSDIHaveTheSamePublicKey() {
    if (services != null) {
        for (TSPServiceType service : services) {
            // both values are mandatory and are supposed to be present at this point
            DigitalIdentityListType sdi = service.getServiceInformation().getServiceDigitalIdentity();
            Set<PublicKey> publicKeySet = new HashSet<PublicKey>();
            Set<X500Principal> subjectSet = new HashSet<X500Principal>();
            for (DigitalIdentityType id : sdi.getDigitalId()) { // 1-2 entries
                byte[] x509Certificate = id.getX509Certificate();
                if (x509Certificate != null) {
                    try {
                        final X509Certificate x509 = DSSUtils.loadCertificate(x509Certificate);
                        publicKeySet.add(x509.getPublicKey());
                        subjectSet.add(x509.getSubjectX500Principal());
                    } catch (DSSException e) {
                        LOG.log(Level.SEVERE, e.getMessage(), e);
                    }
                } else {
                    final String x509SubjectName = id.getX509SubjectName();
                    if (x509SubjectName != null) {
                        subjectSet.add(new X500Principal(x509SubjectName));
                    }
                }
            }

            if (publicKeySet.size() > 1) {
                logger.error(uiKeys.getString("Validation.rule.digitalIdentity.uniquePublicKeyPerService"),
                        service);
            }
            if (subjectSet.size() > 1) {
                logger.error(uiKeys.getString("Validation.rule.digitalIdentity.uniqueSubjectNamePerService"),
                        service);
            }
        }
    }
}

From source file:eu.europa.ec.markt.tlmanager.core.validation.Validation.java

/**
 * 5.5.3 Service digital identity/*from ww w  .j a v  a2s.c  o m*/
 * <p/>
 * The TLSO may list more than one certificate to represent the
 * public key, but only when all those certificates relate to the same public key and have identical
 * subject names
 */
void checkRulePointerToOtherTSLHaveTheSamePublicKey() {
    if (pointers != null) {
        for (OtherTSLPointerType pointer : pointers) {
            final List<DigitalIdentityListType> serviceDigitalIdentity = pointer.getServiceDigitalIdentities()
                    .getServiceDigitalIdentity();
            for (DigitalIdentityListType digitalIdentityListType : serviceDigitalIdentity) {
                Set<PublicKey> publicKeySet = new HashSet<PublicKey>();
                Set<X500Principal> subjectSet = new HashSet<X500Principal>();
                for (DigitalIdentityType id : digitalIdentityListType.getDigitalId()) { // 1-2 entries
                    byte[] x509Certificate = id.getX509Certificate();
                    if (x509Certificate != null) {
                        try {
                            final X509Certificate x509 = DSSUtils.loadCertificate(x509Certificate);
                            publicKeySet.add(x509.getPublicKey());
                            subjectSet.add(x509.getSubjectX500Principal());
                        } catch (DSSException e) {
                            LOG.log(Level.SEVERE, e.getMessage(), e);
                        }
                    }
                }

                if (publicKeySet.size() > 1) {
                    logger.error(uiKeys.getString("Validation.rule.digitalIdentity.uniquePublicKeyPerService"),
                            pointer);
                }
                if (subjectSet.size() > 1) {
                    logger.error(
                            uiKeys.getString("Validation.rule.digitalIdentity.uniqueSubjectNamePerService"),
                            pointer);
                }
            }
        }
    }
}

From source file:org.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override/*from  w w  w . java  2  s.  c  o m*/
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        final String key = ExternalAuthentication.startExternalAuthentication(httpRequest);

        final X509Certificate[] certs = (X509Certificate[]) httpRequest
                .getAttribute("javax.servlet.request.X509Certificate");
        log.debug("{} X.509 Certificate(s) found in request", certs != null ? certs.length : 0);

        if (certs == null || certs.length < 1) {
            log.error("No X.509 Certificates found in request");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    AuthnEventIds.NO_CREDENTIALS);
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        final X509Certificate cert = certs[0];
        log.debug("End-entity X.509 certificate found with subject '{}', issued by '{}'",
                cert.getSubjectDN().getName(), cert.getIssuerDN().getName());

        if (trustEngine != null) {
            try {
                final BasicX509Credential cred = new BasicX509Credential(cert);
                cred.setEntityCertificateChain(Arrays.asList(certs));
                if (trustEngine.validate(cred, new CriteriaSet())) {
                    log.debug("Trust engine validated X.509 certificate");
                } else {
                    log.warn("Trust engine failed to validate X.509 certificate");
                    httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                            AuthnEventIds.INVALID_CREDENTIALS);
                    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                    return;
                }
            } catch (final SecurityException e) {
                log.error("Exception raised by trust engine", e);
                httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_EXCEPTION_KEY, e);
                ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                return;
            }
        }

        final String passthrough = httpRequest.getParameter(PASSTHROUGH_PARAM);
        if (passthrough != null && Boolean.parseBoolean(passthrough)) {
            log.debug("Setting UI passthrough cookie");
            final Cookie cookie = new Cookie(PASSTHROUGH_PARAM, "1");
            cookie.setPath(httpRequest.getContextPath());
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setSecure(true);
            httpResponse.addCookie(cookie);
        }

        final Subject subject = new Subject();
        subject.getPublicCredentials().add(cert);
        subject.getPrincipals().add(cert.getSubjectX500Principal());

        httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);

        //         final String revokeConsent = httpRequest
        //               .getParameter(ProfileInterceptorFlowDescriptor.REVOKE_CONSENT_PARAM);
        //         if (revokeConsent != null
        //               && ("1".equals(revokeConsent) || "true"
        //                     .equals(revokeConsent))) {
        //            httpRequest.setAttribute(
        //                  ExternalAuthentication.REVOKECONSENT_KEY, Boolean.TRUE);
        //         }

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:eu.europa.ec.markt.tlmanager.core.validation.Validation.java

/**
 * History/*w  w w  . j av a 2  s.  c  o m*/
 * <p>
 * The service digital identifier must refer to the SDI described in the Service entity.
 */
private void checkRuleServiceDigitalIdentifier() {
    if (services != null) {
        for (TSPServiceType service : services) {
            DigitalIdentityListType sdi = service.getServiceInformation().getServiceDigitalIdentity();

            byte[] certS = null, skiS = null;
            X500Principal subjectName = null;
            for (DigitalIdentityType dit : sdi.getDigitalId()) {
                if (dit.getX509Certificate() != null) {
                    certS = dit.getX509Certificate();
                    break; // get only the certificate
                }
            }

            X509Certificate certificate = null;
            try {
                certificate = DSSUtils.loadCertificate(new ByteArrayInputStream(certS));

                subjectName = certificate.getSubjectX500Principal();
                skiS = DSSUtils.getSki(certificate);
            } catch (Exception ex) { // catch also potential npe's
                String message = uiKeys.getString("Validation.mandatory.certificate.invalid");
                LOG.log(Level.SEVERE, message + " - " + ex.getMessage());
                logger.error(message, service);
            }

            ServiceHistoryType serviceHistory = service.getServiceHistory();
            if (serviceHistory != null) {
                List<ServiceHistoryInstanceType> serviceHistoryInstance = serviceHistory
                        .getServiceHistoryInstance();
                for (ServiceHistoryInstanceType history : serviceHistoryInstance) {
                    sdi = history.getServiceDigitalIdentity();

                    byte[] certH = null, skiH = null;
                    X500Principal nameH = null;
                    for (DigitalIdentityType dit : sdi.getDigitalId()) {
                        if (dit.getX509Certificate() != null) {
                            certH = dit.getX509Certificate();
                        } else if (dit.getX509SubjectName() != null) {
                            nameH = new X500Principal(dit.getX509SubjectName());
                        } else if (dit.getX509SKI() != null) {
                            skiH = dit.getX509SKI();
                        }
                    }
                    if (certH != null && !Arrays.equals(certH, certS)) {
                        logger.error(uiKeys.getString("Validation.rule.serviceDigitalIdentifier.certMismatch"),
                                history);
                    }

                    if (nameH != null && !nameH.equals(subjectName)) {
                        logger.error(uiKeys.getString("Validation.rule.serviceDigitalIdentifier.snMismatch"),
                                history);
                    }

                    if (skiH != null && skiS != null) {
                        byte[] shorterSki = skiH;
                        byte[] longerSki = skiS;
                        if (skiH.length != skiS.length) {
                            if (skiH.length > skiS.length) {
                                shorterSki = skiS;
                                longerSki = skiH;
                            }
                            longerSki = Arrays.copyOfRange(longerSki, longerSki.length - shorterSki.length,
                                    longerSki.length);
                        }
                        if (!Arrays.equals(shorterSki, longerSki)) {
                            logger.error(
                                    uiKeys.getString("Validation.rule.serviceDigitalIdentifier.skiMismatch"),
                                    history);
                        }
                    }
                }
            }
        }
    }
}

From source file:be.fedict.trust.crl.CrlTrustLinker.java

private TrustLinkerResult processCrl(URI crlUri, X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, BigInteger baseCrlNumber) {

    LOG.debug("CRL URI: " + crlUri);
    X509CRL x509crl = this.crlRepository.findCrl(crlUri, certificate, validationDate);
    if (null == x509crl) {
        return null;
    }//from w w w  .j a v a  2 s. c  o m

    // check CRL integrity
    boolean crlIntegrityResult = checkCrlIntegrity(x509crl, certificate, validationDate);
    if (false == crlIntegrityResult) {
        return null;
    }

    // check CRL signature
    TrustLinkerResult trustResult = TrustValidator.checkSignatureAlgorithm(x509crl.getSigAlgName());
    if (!trustResult.isValid()) {
        return trustResult;
    }

    // we don't support indirect CRLs
    if (isIndirectCRL(x509crl)) {
        LOG.debug("indirect CRL detected");
        return null;
    }

    LOG.debug("CRL number: " + getCrlNumber(x509crl));
    // check delta CRL indicator against completeCrlNuber
    if (null != baseCrlNumber) {
        BigInteger crlNumber = getDeltaCrlIndicator(x509crl);
        if (!baseCrlNumber.equals(crlNumber)) {
            LOG.error("Delta CRL indicator (" + crlNumber + ") not equals base CRL number(" + baseCrlNumber
                    + ")");
            return null;
        }
    }

    // fill up revocation data if not null with this valid CRL
    if (null != revocationData) {
        try {
            revocationData.getCrlRevocationData().add(new CRLRevocationData(x509crl.getEncoded()));
        } catch (CRLException e) {
            LOG.error("CRLException: " + e.getMessage(), e);
            throw new RuntimeException("CRLException : " + e.getMessage(), e);
        }
    }

    boolean revoked = true;
    X509CRLEntry crlEntry = x509crl.getRevokedCertificate(childCertificate.getSerialNumber());
    if (null == crlEntry) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal());
        revoked = false;
    } else if (crlEntry.getRevocationDate().after(validationDate)) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate);
        revoked = false;
    }

    if (null != x509crl.getExtensionValue(X509Extensions.DeltaCRLIndicator.getId())) {
        // Delta CRL
        if (!revoked)
            return null;

    } else {
        // Base CRL, look for delta's
        List<URI> deltaCrlUris = getDeltaCrlUris(x509crl);
        if (null != deltaCrlUris) {
            for (URI deltaCrlUri : deltaCrlUris) {
                LOG.debug("delta CRL: " + deltaCrlUri.toString());
                TrustLinkerResult result = processCrl(deltaCrlUri, childCertificate, certificate,
                        validationDate, revocationData, getCrlNumber(x509crl));
                if (null != result)
                    return result;
            }
        }
    }

    if (!revoked)
        return new TrustLinkerResult(true);

    return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
            "certificate revoked by CRL=" + crlEntry.getSerialNumber());

}

From source file:org.cesecore.certificates.ca.X509CA.java

/**
 * Generate a CRL or a deltaCRL// w  w w . jav a 2  s  .  c  o  m
 * 
 * @param certs
 *            list of revoked certificates
 * @param crlnumber
 *            CRLNumber for this CRL
 * @param isDeltaCRL
 *            true if we should generate a DeltaCRL
 * @param basecrlnumber
 *            caseCRLNumber for a delta CRL, use 0 for full CRLs
 * @param certProfile
 *            certificate profile for CRL Distribution point in the CRL, or null
 * @return CRL
 * @throws CryptoTokenOfflineException
 * @throws IllegalCryptoTokenException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod,
        int crlnumber, boolean isDeltaCRL, int basecrlnumber)
        throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }

    // Make DNs
    final X509Certificate cacert = (X509Certificate) getCACertificate();
    final X500Name issuer;
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        final X500NameStyle nameStyle;
        if (getUsePrintableStringSubjectDN()) {
            nameStyle = PrintableStringNameStyle.INSTANCE;
        } else {
            nameStyle = CeSecoreNameStyle.INSTANCE;
        }
        issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder());
    } else {
        issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded());
    }
    final Date thisUpdate = new Date();
    final Date nextUpdate = new Date();
    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    if (certs != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
        final Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            final RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
        if (log.isDebugEnabled()) {
            log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null);
        if (caSkid != null) {
            // Use subject key id from CA certificate
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid);
            crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
        } else {
            // Generate from SHA1 of public key
            ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken
                    .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN))
                    .getEncoded()));
            try {
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) asn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
            } finally {
                asn1InputStream.close();
            }
        }
    }

    // Authority Information Access  
    final ASN1EncodableVector accessList = new ASN1EncodableVector();
    if (getAuthorityInformationAccess() != null) {
        for (String url : getAuthorityInformationAccess()) {
            if (StringUtils.isNotEmpty(url)) {
                GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier,
                        new DERIA5String(url));
                accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation));
            }
        }
    }
    if (accessList.size() > 0) {
        AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(new DERSequence(accessList));
        // "This CRL extension MUST NOT be marked critical." according to rfc4325
        crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum);
    }
    // CRL Distribution point URI and Freshest CRL DP
    if (getUseCrlDistributionPointOnCrl()) {
        String crldistpoint = getDefaultCRLDistPoint();
        List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint);

        if (distpoints.size() > 0) {
            IssuingDistributionPoint idp = new IssuingDistributionPoint(
                    distpoints.get(0).getDistributionPoint(), false, false, null, false, false);

            // According to the RFC, IDP must be a critical extension.
            // Nonetheless, at the moment, Mozilla is not able to correctly
            // handle the IDP extension and discards the CRL if it is critical.
            crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(),
                    idp);
        }

        if (!isDeltaCRL) {
            String crlFreshestDP = getCADefinedFreshestCRL();
            List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP);
            if (freshestDistPoints.size() > 0) {
                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints
                        .toArray(new DistributionPoint[freshestDistPoints.size()]));

                // According to the RFC, the Freshest CRL extension on a
                // CRL must not be marked as critical. Therefore it is
                // hardcoded as not critical and is independent of
                // getCrlDistributionPointOnCrlCritical().
                crlgen.addExtension(Extension.freshestCRL, false, ext);
            }

        }
    }

    final X509CRLHolder crl;
    if (log.isDebugEnabled()) {
        log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN);
    try {
        final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg)
                .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480);
        crl = crlgen.build(signer);
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL
    // because something is wrong...
    final PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA certificate.");
        }
    } else {
        verifyKey = cryptoToken.getPublicKey(alias);
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA token.");
        }
    }
    try {
        final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey);
        if (!crl.isSignatureValid(verifier)) {
            throw new SignatureException("Error verifying CRL to be returned.");
        }
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    } catch (CertException e) {
        throw new SignatureException(e.getMessage(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    return crl;
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Create a Truststore alias that would be used for adding the given trusted
 * X509 certificate to the Truststore. The alias is cretaed as
 * "trustedcert#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<
 * CERT_SERIAL_NUMBER>/*from   ww w  .  ja v a 2 s. co  m*/
 * 
 * @param cert
 *            certificate to generate the alias for
 * @return the alias for the given certificate
 */
@Override
public String createTrustedCertificateAlias(X509Certificate cert) {
    String ownerDN = cert.getSubjectX500Principal().getName(RFC2253);
    ParsedDistinguishedName parsedDN = dnParser.parseDN(ownerDN);
    String owner;
    String ownerCN = parsedDN.getCN(); // owner's common name
    String ownerOU = parsedDN.getOU();
    String ownerO = parsedDN.getO();
    if (!ownerCN.equals("none")) { // try owner's CN first
        owner = ownerCN;
    } // try owner's OU
    else if (!ownerOU.equals("none")) {
        owner = ownerOU;
    } else if (!ownerO.equals("none")) { // finally use owner's Organisation
        owner = ownerO;
    } else {
        owner = "<Not Part of Certificate>";
    }

    /* Get the hexadecimal representation of the certificate's serial number */
    String serialNumber = new BigInteger(1, cert.getSerialNumber().toByteArray()).toString(16).toUpperCase();

    String issuerDN = cert.getIssuerX500Principal().getName(RFC2253);
    parsedDN = dnParser.parseDN(issuerDN);
    String issuer;
    String issuerCN = parsedDN.getCN(); // issuer's common name
    String issuerOU = parsedDN.getOU();
    String issuerO = parsedDN.getO();
    if (!issuerCN.equals("none")) { // try issuer's CN first
        issuer = issuerCN;
    } // try issuer's OU
    else if (!issuerOU.equals("none")) {
        issuer = issuerOU;
    } else if (!issuerO.equals("none")) { // finally use issuer's
        // Organisation
        issuer = issuerO;
    } else {
        issuer = "<Not Part of Certificate>";
    }

    String alias = "trustedcert#" + owner + "#" + issuer + "#" + serialNumber;
    return alias;
}

From source file:org.cesecore.authentication.SimpleAuthenticationProviderSessionBean.java

/**
 * This is the pug of authentication; loves everybody.
 *///from  w ww  .ja  v a 2s  . co m
@Override
public AuthenticationToken authenticate(AuthenticationSubject subject) {

    // A small check if we have added a "fail" credential to the subject.
    // If we have we will return null, so we can test authentication failure.
    Set<?> usercredentials = subject.getCredentials();
    if ((usercredentials != null) && (usercredentials.size() > 0)) {
        Object o = usercredentials.iterator().next();
        if (o instanceof String) {
            String str = (String) o;
            if (StringUtils.equals("fail", str)) {
                return null;
            }
        }
    }

    X509Certificate certificate = null;
    // If we have a certificate as input, use that, otherwise generate a self signed certificate
    Set<X509Certificate> credentials = new HashSet<X509Certificate>();
    Set<?> inputcreds = subject.getCredentials();
    if (inputcreds != null) {
        for (Object object : inputcreds) {
            if (object instanceof X509Certificate) {
                certificate = (X509Certificate) object;
            }
        }
    }

    // If there was no certificate input, create a self signed
    if (certificate == null) {
        String dn = "C=SE,O=Test,CN=Test"; // default
        // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate.
        if (subject != null) {
            Set<Principal> principals = subject.getPrincipals();
            if ((principals != null) && (principals.size() > 0)) {
                Principal p = principals.iterator().next();
                if (p instanceof X500Principal) {
                    X500Principal xp = (X500Principal) p;
                    dn = xp.getName();
                }
            }
        }
        KeyPair keys = null;
        try {
            keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        } catch (NoSuchAlgorithmException e) {
            throw new InvalidAuthenticationTokenException("Could not create authentication token.", e);
        } catch (NoSuchProviderException e) {
            throw new InvalidAuthenticationTokenException("Could not create authentication token.", e);
        } catch (InvalidAlgorithmParameterException e) {
            throw new InvalidAuthenticationTokenException("Could not create authentication token.", e);
        }
        try {
            certificate = CertTools.genSelfCert(dn, 365, null, keys.getPrivate(), keys.getPublic(),
                    AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true);
        } catch (InvalidKeyException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (CertificateEncodingException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (NoSuchAlgorithmException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (SignatureException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (IllegalStateException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (NoSuchProviderException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        }
    }
    // Add the credentials and new principal
    credentials.add(certificate);
    Set<X500Principal> principals = new HashSet<X500Principal>();
    principals.add(certificate.getSubjectX500Principal());

    // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM.
    AuthenticationToken result = new TestAuthenticationToken(principals, credentials);
    return result;
}

From source file:org.cesecore.mock.authentication.SimpleAuthenticationProviderSessionBean.java

/**
 * This is the pug of authentication; loves everybody.
 *///from w w w .  jav  a 2s  .  c o m
@Override
public AuthenticationToken authenticate(AuthenticationSubject subject) {

    // A small check if we have added a "fail" credential to the subject.
    // If we have we will return null, so we can test authentication failure.
    Set<?> usercredentials = subject.getCredentials();
    if ((usercredentials != null) && (usercredentials.size() > 0)) {
        Object o = usercredentials.iterator().next();
        if (o instanceof String) {
            String str = (String) o;
            if (StringUtils.equals("fail", str)) {
                if (log.isDebugEnabled()) {
                    log.debug("Found a 'fail' credential, returning null");
                }
                return null;
            }
        }
    }

    X509Certificate certificate = null;
    // If we have a certificate as input, use that, otherwise generate a self signed certificate
    Set<?> inputcreds = subject.getCredentials();
    if (inputcreds != null) {
        for (Object object : inputcreds) {
            if (object instanceof X509Certificate) {
                certificate = (X509Certificate) object;
                if (log.isDebugEnabled()) {
                    log.debug("Found a certificate credential that we will use, fp="
                            + CertTools.getFingerprintAsString(certificate));
                }
            }
        }
    }

    // If there was no certificate input, create a self signed
    if (certificate == null) {
        if (log.isDebugEnabled()) {
            log.debug("No certificate input, will create a self-signed one");
        }
        String dn = DEFAULT_DN;
        // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate.
        if (subject != null) {
            Set<Principal> principals = subject.getPrincipals();
            if ((principals != null) && (principals.size() > 0)) {
                Principal p = principals.iterator().next();
                if (p instanceof X500Principal) {
                    X500Principal xp = (X500Principal) p;
                    dn = xp.getName();
                }
            }
        }
        KeyPair keys = null;
        try {
            keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        } catch (InvalidAlgorithmParameterException e) {
            throw new InvalidAuthenticationTokenException("Could not create authentication token.", e);
        }
        try {
            certificate = CertTools.genSelfCert(dn, 365, null, keys.getPrivate(), keys.getPublic(),
                    AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true);
        } catch (CertificateEncodingException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (IllegalStateException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (OperatorCreationException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (CertificateException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (IOException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        }
        if (log.isDebugEnabled()) {
            log.debug("Creates a self signed authentication certificate, fp="
                    + CertTools.getFingerprintAsString(certificate));
        }
    }
    // Add the credentials and new principal
    Set<X509Certificate> credentials = new HashSet<X509Certificate>();
    credentials.add(certificate);
    Set<X500Principal> principals = new HashSet<X500Principal>();
    principals.add(certificate.getSubjectX500Principal());

    // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM.
    AuthenticationToken result = new TestX509CertificateAuthenticationToken(principals, credentials);
    return result;
}

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

/**
 * 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   w w w  .j  a v a  2 s.c  o  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);
                }
            }
        }
    }
}