Example usage for java.security.cert X509Certificate getSubjectDN

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

Introduction

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

Prototype

public abstract Principal getSubjectDN();

Source Link

Document

Denigrated, replaced by #getSubjectX500Principal() .

Usage

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

private void logAdminName(final AuthenticationToken admin, final IPatternLogger logger) {
    // Log certificate info
    final X509Certificate cert = ((X509CertificateAuthenticationToken) admin).getCertificate();
    logger.paramPut(TransactionTags.ADMIN_DN.toString(), cert.getSubjectDN().toString());
    logger.paramPut(TransactionTags.ADMIN_ISSUER_DN.toString(), cert.getIssuerDN().toString());

    // Log IP address
    MessageContext msgctx = wsContext.getMessageContext();
    HttpServletRequest request = (HttpServletRequest) msgctx.get(MessageContext.SERVLET_REQUEST);
    logger.paramPut(TransactionTags.ADMIN_REMOTE_IP.toString(), request.getRemoteAddr());
    String addr = request.getHeader("X-Forwarded-For");
    if (addr != null)
        addr = addr.replaceAll("[^a-zA-Z0-9.:-_]", "?");
    logger.paramPut(TransactionTags.ADMIN_FORWARDED_IP.toString(), addr);
}

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

@Override
public List<UserDataSourceVOWS> fetchUserData(List<String> userDataSourceNames, String searchString)
        throws UserDataSourceException, EjbcaException, AuthorizationDeniedException {

    final AuthenticationToken admin;
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, caSession,
            certificateProfileSession, certificateStoreSession, endEntityAccessSession, endEntityProfileSession,
            hardTokenSession, endEntityManagementSession, webAuthenticationSession,
            cryptoTokenManagementSession);

    if (WebServiceConfiguration.getNoAuthorizationOnFetchUserData()) {
        final AuthenticationToken tmp = ejbhelper.getAdmin(true);
        // We know client certificate is needed, so no other authentication tokens can exist
        X509Certificate admincert = ((X509CertificateAuthenticationToken) tmp).getCertificate();
        admin = new AlwaysAllowLocalAuthenticationToken(new X509Principal(admincert.getSubjectDN().getName()));
    } else {/*from ww  w.  ja  v a  2s  . co  m*/
        admin = ejbhelper.getAdmin();
    }

    final ArrayList<UserDataSourceVOWS> retval = new ArrayList<UserDataSourceVOWS>();

    final IPatternLogger logger = TransactionLogger.getPatternLogger();
    logAdminName(admin, logger);
    try {
        final ArrayList<Integer> userDataSourceIds = new ArrayList<Integer>();
        {
            final Iterator<String> iter = userDataSourceNames.iterator();
            while (iter.hasNext()) {
                final String name = iter.next();
                final int id = userDataSourceSession.getUserDataSourceId(admin, name);
                if (id != 0) {
                    userDataSourceIds.add(Integer.valueOf(id));
                } else {
                    log.error("Error User Data Source with name : " + name + " doesn't exist.");
                }
            }
        }
        {
            final Iterator<UserDataSourceVO> iter = userDataSourceSession
                    .fetch(admin, userDataSourceIds, searchString).iterator();
            while (iter.hasNext()) {
                UserDataSourceVO next = iter.next();
                retval.add(new UserDataSourceVOWS(
                        ejbhelper.convertEndEntityInformation(next.getEndEntityInformation()),
                        next.getIsFieldModifyableSet()));
            }
        }
    } catch (CADoesntExistsException e) { // EJBException, ClassCastException, ...
        throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.CA_NOT_EXISTS, Level.INFO);
    } catch (RuntimeException e) { // EJBException, ClassCastException, ...
        throw EjbcaWSHelper.getInternalException(e, logger);
    } finally {
        logger.writeln();
        logger.flush();
    }
    return retval;
}

From source file:eu.stork.peps.auth.engine.STORKSAMLEngine.java

/**
 * Gets the country from X.509 Certificate.
 * /*from w  ww.j  a  v  a2s  .c  o  m*/
 * @param keyInfo the key info
 * 
 * @return the country
 */
private String getCountry(final KeyInfo keyInfo) {
    LOG.debug("Recover country information.");

    String result = "";
    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);

        String distName = cert.getSubjectDN().toString();

        distName = StringUtils.deleteWhitespace(StringUtils.upperCase(distName));

        final String countryCode = "C=";
        final int init = distName.indexOf(countryCode);

        if (init > StringUtils.INDEX_NOT_FOUND) { // Exist country code.
            int end = distName.indexOf(',', init);

            if (end <= StringUtils.INDEX_NOT_FOUND) {
                end = distName.length();
            }

            if (init < end && end > StringUtils.INDEX_NOT_FOUND) {
                result = distName.substring(init + countryCode.length(), end);
                //It must be a two characters value
                if (result.length() > 2) {
                    result = result.substring(0, 2);
                }
            }
        }

    } catch (CertificateException e) {
        LOG.error("Procces getCountry from certificate.");
    }
    return result.trim();
}

From source file:org.cesecore.certificates.ocsp.CanLogCache.java

private BasicOCSPResp generateBasicOcspResp(OCSPReq ocspRequest, X509Extensions exts,
        List<OCSPResponseItem> responses, String sigAlg, X509Certificate signerCert, PrivateKey signerKey,
        String provider, X509Certificate[] chain, int respIdType)
        throws NotSupportedException, OCSPException, NoSuchProviderException, CryptoTokenOfflineException {
    BasicOCSPResp returnval = null;/*from  w  ww. ja v a2 s  .  c  o  m*/
    BasicOCSPRespGenerator basicRes = null;
    basicRes = createOcspResponseGenerator(ocspRequest, signerCert, respIdType);
    if (responses != null) {
        for (OCSPResponseItem item : responses) {
            basicRes.addResponse(item.getCertID(), item.getCertStatus(), item.getThisUpdate(),
                    item.getNextUpdate(), null);
        }
    }
    if (exts != null) {
        @SuppressWarnings("rawtypes")
        Enumeration oids = exts.oids();
        if (oids.hasMoreElements()) {
            basicRes.setResponseExtensions(exts);
        }
    }

    /*
     * The below code breaks the EJB standard by creating its own thread pool and creating a single thread (of the HsmResponseThread 
     * type). The reason for this is that the HSM may deadlock when requesting an OCSP response, which we need to guard against. Since 
     * there is no way of performing this action within the EJB3.0 standard, we are consciously creating threads here. 
     * 
     * Note that this does in no way break the spirit of the EJB standard, which is to not interrupt EJB's transaction handling by 
     * competing with its own thread pool, since these operations have no database impact.
     */

    final ExecutorService service = Executors.newFixedThreadPool(1);
    final Future<BasicOCSPResp> task = service
            .submit(new HsmResponseThread(basicRes, sigAlg, signerKey, chain, provider));

    try {
        returnval = task.get(HsmResponseThread.HSM_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new Error("OCSP response retrieval was interrupted while running. This should not happen", e);
    } catch (ExecutionException e) {
        throw new OcspFailureException("Failure encountered while retrieving OCSP response.", e);
    } catch (TimeoutException e) {
        throw new CryptoTokenOfflineException("HSM timed out while trying to get OCSP response", e);
    }

    if (log.isDebugEnabled()) {
        log.debug("Signing OCSP response with OCSP signer cert: " + signerCert.getSubjectDN().getName());
        RespID respId = null;
        if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) {
            respId = new RespID(signerCert.getSubjectX500Principal());
        } else {
            respId = new RespID(signerCert.getPublicKey());
        }
        if (!returnval.getResponderId().equals(respId)) {
            log.error("Response responderId does not match signer certificate responderId!");
        }
        boolean verify = returnval.verify(signerCert.getPublicKey(), "BC");
        if (verify) {
            log.debug("The OCSP response is verifying.");
        } else {
            log.error("The response is NOT verifying!");
        }
    }
    return returnval;
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

protected X509Certificate createCertificateFromCSR(PKCS10CertificationRequest csr) throws CertException {
    X509Certificate cert;
    try {//w w w  .  j av  a  2s  . c  o  m
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(getRootCertificate().getIssuerX500Principal());
        certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
        certGen.setNotBefore(getCertStartDate());
        certGen.setNotAfter(getCertEndDate());
        certGen.setPublicKey(csr.getPublicKey("BC"));
        certGen.setSignatureAlgorithm(CERT_SIGNATURE_ALGORITHM);
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(getRootCertificate()));
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

        ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes();
        for (int i = 0; i != attributes.size(); i++) {
            Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
            if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));
                @SuppressWarnings("rawtypes")
                Enumeration e = extensions.oids();
                while (e.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                    X509Extension ext = extensions.getExtension(oid);
                    certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
                }
            }
        }

        KeyPair rootKeyPair = getKeyPair(rootService.getRootKeyStore(), rootService.getRootKeyAlias(),
                rootService.getRootCertificateAlias(), rootService.getRootKeyPassword());
        cert = certGen.generate(rootKeyPair.getPrivate(), "BC");
    } catch (CertificateParsingException e) {
        throw new CertException(e);
    } catch (CertificateEncodingException e) {
        throw new CertException(e);
    } catch (InvalidKeyException e) {
        throw new CertException(e);
    } catch (IllegalStateException e) {
        throw new CertException(e);
    } catch (NoSuchProviderException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (java.security.SignatureException e) {
        throw new CertException(e);
    }
    LOG.debug("Certificate generated for subject: " + cert.getSubjectDN());
    return cert;
}

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

/**
 * Search for e-mail address, first in SubjectAltName (as in PKIX recommendation) then in subject DN. Original author: Marco Ferrante, (c) 2005
 * CSITA - University of Genoa (Italy)//from  w  ww . j  ava  2s  .c o m
 * 
 * @param certificate
 * @return subject email or null if not present in certificate
 */
public static String getEMailAddress(Certificate certificate) {
    log.debug("Searching for EMail Address in SubjectAltName");
    if (certificate == null) {
        return null;
    }
    if (certificate instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) certificate;
        try {
            if (x509cert.getSubjectAlternativeNames() != null) {
                for (List<?> item : x509cert.getSubjectAlternativeNames()) {
                    Integer type = (Integer) item.get(0);
                    if (type.intValue() == 1) {
                        return (String) item.get(1);
                    }
                }
            }
        } catch (CertificateParsingException e) {
            log.error("Error parsing certificate: ", e);
        }
        log.debug("Searching for EMail Address in Subject DN");
        ArrayList<String> emails = CertTools.getEmailFromDN(x509cert.getSubjectDN().getName());
        if (!emails.isEmpty()) {
            return (String) emails.get(0);
        }
    }
    return null;
}

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

@Override
public List<TokenCertificateResponseWS> genTokenCertificates(UserDataVOWS userDataWS,
        List<TokenCertificateRequestWS> tokenRequests, HardTokenDataWS hardTokenDataWS,
        boolean overwriteExistingSN, boolean revokePreviousCards)
        throws CADoesntExistsException, AuthorizationDeniedException, WaitingForApprovalException,
        HardTokenExistsException, UserDoesntFullfillEndEntityProfile, ApprovalException, EjbcaException,
        ApprovalRequestExpiredException, ApprovalRequestExecutionException {
    final ArrayList<TokenCertificateResponseWS> retval = new ArrayList<TokenCertificateResponseWS>();

    final EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession,
            caSession, certificateProfileSession, certificateStoreSession, endEntityAccessSession,
            endEntityProfileSession, hardTokenSession, endEntityManagementSession, webAuthenticationSession,
            cryptoTokenManagementSession);
    AuthenticationToken admin = ejbhelper.getAdmin(true);
    int endEntityProfileId = 0;
    boolean hardTokenExists = false;
    boolean userExists = false;

    boolean approvalSuccessfullStep1 = false;
    boolean isRejectedStep1 = false;

    // Get Significant user Id
    final CAInfo significantcAInfo;
    final ArrayList<java.security.cert.Certificate> genCertificates = new ArrayList<java.security.cert.Certificate>();
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
    logAdminName(admin, logger);/*w  w w .  ja v  a2  s .c  o m*/
    final AuthenticationToken intAdmin = new AlwaysAllowLocalAuthenticationToken(
            new UsernamePrincipal("EJBCAWS.genTokenCertificates"));
    try {
        significantcAInfo = caSession.getCAInfo(intAdmin, userDataWS.getCaName());
        if (significantcAInfo == null) {
            throw EjbcaWSHelper.getEjbcaException(
                    "Error the given CA : " + userDataWS.getCaName() + " could not be found.", logger,
                    ErrorCode.CA_NOT_EXISTS, null);
        }

        EndEntityInformation endEntityInformation = endEntityAccessSession.findUser(intAdmin,
                userDataWS.getUsername());
        if (endEntityInformation != null) {
            endEntityProfileId = endEntityInformation.getEndEntityProfileId();
            userExists = true;
        } else {
            try {
                endEntityProfileId = endEntityProfileSession
                        .getEndEntityProfileId(userDataWS.getEndEntityProfileName());
            } catch (EndEntityProfileNotFoundException e) {
                throw EjbcaWSHelper.getEjbcaException("Error given end entity profile : "
                        + userDataWS.getEndEntityProfileName() + " could not be found", logger,
                        ErrorCode.EE_PROFILE_NOT_EXISTS, null);
            }
        }

        // Approval request if we require approvals to generate token certificates
        ApprovalRequest ar = null;
        if (ejbhelper.isAdmin()) {
            final List<String> rules = new ArrayList<String>();
            rules.add(StandardRules.CREATECERT.resource());
            rules.add(AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS);
            rules.add(StandardRules.CAACCESS.resource() + significantcAInfo.getCAId());
            if (overwriteExistingSN) {
                rules.add(AccessRulesConstants.REGULAR_REVOKEENDENTITY);
                rules.add(AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                        + AccessRulesConstants.REVOKE_END_ENTITY);
            }
            if (userExists) {
                rules.add(AccessRulesConstants.REGULAR_EDITENDENTITY);
                rules.add(AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                        + AccessRulesConstants.EDIT_END_ENTITY);
            } else {
                rules.add(AccessRulesConstants.REGULAR_CREATEENDENTITY);
                rules.add(AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                        + AccessRulesConstants.CREATE_END_ENTITY);
            }
            String[] rulesArray = rules.toArray(new String[rules.size()]);
            if (!authorizationSession.isAuthorizedNoLogging(admin, rulesArray)) {
                final String msg = intres.getLocalizedMessage("authorization.notuathorizedtoresource",
                        Arrays.toString(rulesArray), null);
                throw new AuthorizationDeniedException(msg);
            }
        } else {
            if (WebServiceConfiguration.getApprovalForGenTokenCertificates()) {
                ar = new GenerateTokenApprovalRequest(userDataWS.getUsername(), userDataWS.getSubjectDN(),
                        hardTokenDataWS.getLabel(), admin, null,
                        WebServiceConfiguration.getNumberOfRequiredApprovals(), significantcAInfo.getCAId(),
                        endEntityProfileId);
                int status = ApprovalDataVO.STATUS_REJECTED;
                try {
                    status = approvalSession.isApproved(admin, ar.generateApprovalId(), 1);
                    approvalSuccessfullStep1 = (status == ApprovalDataVO.STATUS_APPROVED);
                    isRejectedStep1 = (status == ApprovalDataVO.STATUS_REJECTED);
                    if (status == ApprovalDataVO.STATUS_APPROVED) {
                        ApprovalDataVO approvalDataVO = approvalSession.findNonExpiredApprovalRequest(intAdmin,
                                ar.generateApprovalId());
                        String originalDN = ((GenerateTokenApprovalRequest) approvalDataVO.getApprovalRequest())
                                .getDN();
                        userDataWS.setSubjectDN(originalDN); // replace requested DN with original DN to make sure nothing have changed.
                    } else if (status == ApprovalDataVO.STATUS_REJECTED) {
                        throw new ApprovalRequestExecutionException(
                                "The approval for id " + ar.generateApprovalId() + " has been rejected.");
                    } else if (status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
                            || status == ApprovalDataVO.STATUS_EXPIRED) {
                        throw new ApprovalException(
                                "The approval for id " + ar.generateApprovalId() + " has expired.");
                    } else {
                        throw new WaitingForApprovalException("The approval for id " + ar.generateApprovalId()
                                + " have not yet been approved", ar.generateApprovalId());
                    }
                } catch (ApprovalException e) {
                    approvalSession.addApprovalRequest(admin, ar);
                    throw new WaitingForApprovalException("Approval request with id " + ar.generateApprovalId()
                            + " have been added for approval.", ar.generateApprovalId());
                }
            } else {
                throw new AuthorizationDeniedException();
            }
        }

        if (ar != null && isRejectedStep1) {
            throw new ApprovalRequestExecutionException(
                    "The approval for id " + ar.generateApprovalId() + " has been rejected.");
        }

        if (ar != null && !approvalSuccessfullStep1) {
            throw new WaitingForApprovalException(
                    "The approval for id " + ar.generateApprovalId() + " has not yet been approved",
                    ar.generateApprovalId());
        }

        if (ar != null) {
            // We need to create a new AuthenticationToken here that has the "name" of the admin making the request, but that 
            // behaves like an "AlwaysAllowedAuthenticationToken". This is because the request admin does not have privileges, 
            // but we want to log as if the requesting admin performed actions below.
            final Set<? extends Principal> principals = admin.getPrincipals();
            Principal p = null;
            if (!principals.isEmpty()) {
                p = principals.iterator().next();
            } else {
                final Set<?> credentials = admin.getCredentials();
                if (!credentials.isEmpty()) {
                    final Object o = credentials.iterator().next();
                    if (o instanceof X509Certificate) {
                        final X509Certificate cert = (X509Certificate) o;
                        p = new X500Principal(cert.getSubjectDN().getName());
                    }
                } else {
                    log.error("Admin does not have neither Principals nor Credentials");
                }
            }
            admin = new AlwaysAllowLocalAuthenticationToken(p);
        }

        hardTokenExists = hardTokenSession.existsHardToken(hardTokenDataWS.getHardTokenSN());
        if (hardTokenExists) {
            if (overwriteExistingSN) {
                // fetch all old certificates and revoke them.
                Collection<java.security.cert.Certificate> currentCertificates = hardTokenSession
                        .findCertificatesInHardToken(hardTokenDataWS.getHardTokenSN());
                HardTokenInformation currentHardToken = hardTokenSession.getHardToken(admin,
                        hardTokenDataWS.getHardTokenSN(), false);
                Iterator<java.security.cert.Certificate> iter = currentCertificates.iterator();
                while (iter.hasNext()) {
                    java.security.cert.X509Certificate nextCert = (java.security.cert.X509Certificate) iter
                            .next();
                    try {
                        endEntityManagementSession.revokeCert(admin, CertTools.getSerialNumber(nextCert),
                                CertTools.getIssuerDN(nextCert), RevokedCertInfo.REVOCATION_REASON_SUPERSEDED);
                    } catch (AlreadyRevokedException e) {
                        // Ignore previously revoked certificates
                    } catch (FinderException e) {
                        throw EjbcaWSHelper.getEjbcaException(
                                "Error revoking old certificate, the user : " + currentHardToken.getUsername()
                                        + " of the old certificate couldn't be found in database.",
                                logger, ErrorCode.USER_NOT_FOUND, null);
                    }
                }

            } else {
                throw new HardTokenExistsException(
                        "Error hard token with sn " + hardTokenDataWS.getHardTokenSN() + " already exists.");
            }

        }

        if (revokePreviousCards) {
            List<HardTokenDataWS> htd = getHardTokenDatas(admin, userDataWS.getUsername(), false, true, logger);
            Iterator<HardTokenDataWS> htdIter = htd.iterator();

            while (htdIter.hasNext()) {
                HardTokenDataWS toRevoke = htdIter.next();
                try {
                    if (hardTokenDataWS.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD)
                            && toRevoke.getLabel() != null
                            && !toRevoke.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD)) {

                        // Token have extended key usage MS Logon, don't revoke it
                        Iterator<java.security.cert.Certificate> revokeCerts = hardTokenSession
                                .findCertificatesInHardToken(toRevoke.getHardTokenSN()).iterator();

                        while (revokeCerts.hasNext()) {
                            X509Certificate next = (X509Certificate) revokeCerts.next();
                            try {
                                if (WebServiceConfiguration.getSuspendAllCertificates()
                                        || next.getExtendedKeyUsage() == null || !next.getExtendedKeyUsage()
                                                .contains(KeyPurposeId.id_kp_smartcardlogon.getId())) {
                                    endEntityManagementSession.revokeCert(admin, next.getSerialNumber(),
                                            CertTools.getIssuerDN(next),
                                            RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                                }
                            } catch (CertificateParsingException e) {
                                log.error(e);
                            } catch (FinderException e) {
                                log.error(e);
                            }
                        }

                    } else {
                        revokeToken(admin, toRevoke.getHardTokenSN(),
                                RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, logger);
                    }
                } catch (AlreadyRevokedException e) {
                    // Do nothing
                }
            }
        }

        try {
            // Check if the userdata exist and edit/add it depending on which
            String password = PasswordGeneratorFactory
                    .getInstance(PasswordGeneratorFactory.PASSWORDTYPE_ALLPRINTABLE).getNewPassword(8, 8);
            EndEntityInformation userData = ejbhelper.convertUserDataVOWS(admin, userDataWS);
            userData.setPassword(password);
            if (userExists) {
                endEntityManagementSession.changeUser(admin, userData, true);
            } else {
                endEntityManagementSession.addUser(admin, userData, true);
            }

            Date bDate = new Date(System.currentTimeMillis() - (10 * 60 * 1000));

            Iterator<TokenCertificateRequestWS> iter = tokenRequests.iterator();
            while (iter.hasNext()) {
                TokenCertificateRequestWS next = iter.next();

                int certificateProfileId = certificateProfileSession
                        .getCertificateProfileId(next.getCertificateProfileName());
                if (certificateProfileId == 0) {
                    EjbcaWSHelper
                            .getEjbcaException(
                                    "Error the given Certificate Profile : " + next.getCertificateProfileName()
                                            + " couldn't be found.",
                                    logger, ErrorCode.CERT_PROFILE_NOT_EXISTS, null);
                }

                Date eDate = null;

                if (next.getValidityIdDays() != null) {
                    try {
                        long validity = Long.parseLong(next.getValidityIdDays());
                        eDate = new Date(System.currentTimeMillis() + (validity * 3600 * 24 * 1000));
                    } catch (NumberFormatException e) {
                        EjbcaWSHelper.getEjbcaException("Error : Validity in Days must be a number", logger,
                                ErrorCode.BAD_VALIDITY_FORMAT, null);
                    }
                }

                CAInfo cAInfo = caSession.getCAInfo(admin, next.getCAName());
                if (cAInfo == null) {
                    throw EjbcaWSHelper.getEjbcaException(
                            "Error the given CA : " + next.getCAName() + " couldn't be found.", logger,
                            ErrorCode.CA_NOT_EXISTS, null);
                }

                if (!authorizationSession.isAuthorizedNoLogging(admin,
                        StandardRules.CAACCESS.resource() + cAInfo.getCAId())) {
                    final String msg = intres.getLocalizedMessage("authorization.notuathorizedtoresource",
                            StandardRules.CAACCESS.resource() + cAInfo.getCAId(), null);
                    throw new AuthorizationDeniedException(msg);
                }
                if (next.getType() == HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST) {
                    userData.setCertificateProfileId(certificateProfileId);
                    userData.setCAId(cAInfo.getCAId());
                    userData.setPassword(password);
                    userData.setStatus(EndEntityConstants.STATUS_NEW);
                    endEntityManagementSession.changeUser(admin, userData, false);
                    PKCS10RequestMessage pkcs10req = new PKCS10RequestMessage(next.getPkcs10Data());
                    java.security.cert.Certificate cert;
                    if (eDate == null) {
                        cert = signSession.createCertificate(admin, userData.getUsername(), password,
                                pkcs10req.getRequestPublicKey());
                    } else {
                        cert = signSession.createCertificate(admin, userData.getUsername(), password,
                                pkcs10req.getRequestPublicKey(), -1, bDate, eDate);
                    }

                    genCertificates.add(cert);
                    retval.add(new TokenCertificateResponseWS(new Certificate(cert)));
                } else if (next.getType() == HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST) {

                    if (!next.getTokenType().equals(HardTokenConstants.TOKENTYPE_PKCS12)) {
                        throw EjbcaWSHelper.getEjbcaException(
                                "Unsupported Key Store Type : " + next.getTokenType() + " only "
                                        + HardTokenConstants.TOKENTYPE_PKCS12 + " is supported",
                                logger, ErrorCode.NOT_SUPPORTED_KEY_STORE, null);
                    }
                    KeyPair keys = KeyTools.genKeys(next.getKeyspec(), next.getKeyalg());
                    userData.setCertificateProfileId(certificateProfileId);
                    userData.setCAId(cAInfo.getCAId());
                    userData.setPassword(password);
                    userData.setStatus(EndEntityConstants.STATUS_NEW);
                    endEntityManagementSession.changeUser(admin, userData, true);
                    X509Certificate cert;
                    if (eDate == null) {
                        cert = (X509Certificate) signSession.createCertificate(admin, userData.getUsername(),
                                password, keys.getPublic());
                    } else {
                        cert = (X509Certificate) signSession.createCertificate(admin, userData.getUsername(),
                                password, keys.getPublic(), -1, bDate, eDate);
                    }

                    genCertificates.add(cert);
                    // Generate Keystore
                    // Fetch CA Cert Chain.           
                    Collection<java.security.cert.Certificate> chain = caSession
                            .getCAInfo(admin, cAInfo.getCAId()).getCertificateChain();
                    String alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");
                    if (alias == null) {
                        alias = userData.getUsername();
                    }
                    java.security.KeyStore pkcs12 = KeyTools.createP12(alias, keys.getPrivate(), cert, chain);

                    retval.add(new TokenCertificateResponseWS(new KeyStore(pkcs12, userDataWS.getPassword())));
                } else {
                    throw EjbcaWSHelper.getEjbcaException(
                            "Error in request, only REQUESTTYPE_PKCS10_REQUEST and REQUESTTYPE_KEYSTORE_REQUEST are supported token requests.",
                            logger, ErrorCode.NOT_SUPPORTED_REQUEST_TYPE, null);
                }
            }

        } catch (Exception e) {
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            endEntityManagementSession.setUserStatus(admin, userDataWS.getUsername(),
                    EndEntityConstants.STATUS_GENERATED);
        }

        // Add hard token data
        HardToken hardToken;
        String signatureInitialPIN = "";
        String signaturePUK = "";
        String basicInitialPIN = "";
        String basicPUK = "";
        Iterator<PinDataWS> iter = hardTokenDataWS.getPinDatas().iterator();
        while (iter.hasNext()) {
            PinDataWS pinData = iter.next();
            switch (pinData.getType()) {
            case HardTokenConstants.PINTYPE_BASIC:
                basicInitialPIN = pinData.getInitialPIN();
                basicPUK = pinData.getPUK();
                break;
            case HardTokenConstants.PINTYPE_SIGNATURE:
                signatureInitialPIN = pinData.getInitialPIN();
                signaturePUK = pinData.getPUK();
                break;
            default:
                throw EjbcaWSHelper.getEjbcaException("Unsupported PIN Type " + pinData.getType(), logger,
                        ErrorCode.NOT_SUPPORTED_PIN_TYPE, null);
            }
        }
        int tokenType = SwedishEIDHardToken.THIS_TOKENTYPE;
        switch (hardTokenDataWS.getTokenType()) {
        case HardTokenConstants.TOKENTYPE_SWEDISHEID:
            hardToken = new SwedishEIDHardToken(basicInitialPIN, basicPUK, signatureInitialPIN, signaturePUK,
                    0);
            break;
        case HardTokenConstants.TOKENTYPE_ENHANCEDEID:
            hardToken = new EnhancedEIDHardToken(signatureInitialPIN, signaturePUK, basicInitialPIN, basicPUK,
                    false, 0);
            tokenType = EnhancedEIDHardToken.THIS_TOKENTYPE;
            break;
        default:
            throw EjbcaWSHelper.getEjbcaException("Unsupported Token Type : " + hardTokenDataWS.getTokenType(),
                    logger, ErrorCode.NOT_SUPPORTED_TOKEN_TYPE, null);

        }

        hardToken.setLabel(hardTokenDataWS.getLabel());
        if (overwriteExistingSN) {
            if (hardTokenExists) {
                try {
                    hardTokenSession.removeHardToken(admin, hardTokenDataWS.getHardTokenSN());
                } catch (HardTokenDoesntExistsException e) {
                    throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.HARD_TOKEN_NOT_EXISTS,
                            Level.ERROR);
                }
            }
        }
        hardTokenSession.addHardToken(admin, hardTokenDataWS.getHardTokenSN(), userDataWS.getUsername(),
                significantcAInfo.getSubjectDN(), tokenType, hardToken, genCertificates,
                hardTokenDataWS.getCopyOfSN());

        if (ar != null) {
            approvalSession.markAsStepDone(admin, ar.generateApprovalId(),
                    GenerateTokenApprovalRequest.STEP_1_GENERATETOKEN);
        }
    } catch (FinderException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (RuntimeException e) { // EJBException, ClassCastException, ...
        throw EjbcaWSHelper.getInternalException(e, logger);
    } finally {
        logger.writeln();
        logger.flush();
    }
    return retval;
}

From source file:com.vmware.identity.idm.server.config.directory.DirectoryConfigStore.java

private boolean isIssuedByCert(List<Certificate> certChain, X509Certificate certToCheck) {
    if (certChain == null || certChain.isEmpty())
        return false;

    for (Certificate cert : certChain) {
        X509Certificate x509Cert = (X509Certificate) cert;
        if (x509Cert.getSubjectDN().getName().compareToIgnoreCase(certToCheck.getIssuerDN().getName()) == 0) {
            return true;
        }/*from   w w w  .jav a  2s .c o m*/
    }

    return false;
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

/**
 * Test method for creating/editing a user a requesting a certificate in a single transaction.
 *///from  ww w.j  a  va 2s. co  m
protected void certificateRequest() throws Exception {

    final UserDataVOWS userData1 = getUserData(CA1_WSTESTUSER1);
    ErrorCode errorCode = certreqInternal(userData1, getP10(), CertificateHelper.CERT_REQ_TYPE_PKCS10);
    assertNull("PKCS#10 request resulted in error code: "
            + (errorCode == null ? "" : errorCode.getInternalErrorCode()), errorCode);
    errorCode = certreqInternal(userData1, CRMF, CertificateHelper.CERT_REQ_TYPE_CRMF);
    assertNull("CRMF request resulted in error code: "
            + (errorCode == null ? "" : errorCode.getInternalErrorCode()), errorCode);
    errorCode = certreqInternal(userData1, SPCAK, CertificateHelper.CERT_REQ_TYPE_SPKAC);
    assertNull("SPKAC request resulted in error code: "
            + (errorCode == null ? "" : errorCode.getInternalErrorCode()), errorCode);
    errorCode = certreqInternal(userData1, PUBLICKEY_PEM, CertificateHelper.CERT_REQ_TYPE_PUBLICKEY);
    assertNull("PUBLICKEY request resulted in error code: "
            + (errorCode == null ? "" : errorCode.getInternalErrorCode()), errorCode);
    errorCode = certreqInternal(userData1, PUBLICKEY_BASE64, CertificateHelper.CERT_REQ_TYPE_PUBLICKEY);
    assertNull("PUBLICKEY request resulted in error code: "
            + (errorCode == null ? "" : errorCode.getInternalErrorCode()), errorCode);

    // Test with custom extensions
    final AuthenticationToken admin = new TestAlwaysAllowLocalAuthenticationToken(
            new UsernamePrincipal("SYSTEMTEST"));

    userData1.setStatus(UserDataVOWS.STATUS_NEW);
    userData1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED);
    userData1.setEndEntityProfileName(WS_EEPROF_EI);
    userData1.setCertificateProfileName(WS_CERTPROF_EI);
    ejbcaraws.editUser(userData1);
    CertificateResponse certificateResponse = ejbcaraws.certificateRequest(userData1, getP10(),
            CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE);
    X509Certificate cert = certificateResponse.getCertificate();
    byte[] ext = cert.getExtensionValue("1.2.3.4");
    // Certificate profile did not allow extension override
    assertNull("no extension should exist", ext);
    // Allow extension override
    CertificateProfile profile = certificateProfileSession.getCertificateProfile(WS_CERTPROF_EI);
    profile.setAllowExtensionOverride(true);
    certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile);
    // Now our extension should be possible to get in there
    try {
        ejbcaraws.editUser(userData1);
        certificateResponse = ejbcaraws.certificateRequest(userData1, getP10(),
                CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE);
        cert = certificateResponse.getCertificate();
        assertNotNull(cert);
        assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString());
        ext = cert.getExtensionValue("1.2.3.4");
        assertNotNull("there should be an extension", ext);
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(ext));
        try {
            DEROctetString oct = (DEROctetString) (asn1InputStream.readObject());
            assertEquals("Extension did not have the correct value", "foo123",
                    (new String(oct.getOctets())).trim());
        } finally {
            asn1InputStream.close();
        }
    } finally {
        // restore
        profile.setAllowExtensionOverride(false);
        certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile);
    }

    // Make a test with EV TLS DN components
    try {
        final UserDataVOWS userData2 = getUserData(CA1_WSTESTUSER1);
        userData2.setUsername("EVTLSEJBCAWSTEST");
        userData2.setSubjectDN(
                "CN=EVTLSEJBCAWSTEST,JurisdictionCountry=DE,JurisdictionState=Stockholm,JurisdictionLocality=Solna");
        try {
            certificateResponse = ejbcaraws.certificateRequest(userData2, getP10(),
                    CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE);
        } catch (EjbcaException_Exception e) {
            errorCode = e.getFaultInfo().getErrorCode();
            log.info(errorCode.getInternalErrorCode(), e);
            assertNotNull("error code should not be null", errorCode);
            fail("certificate request with EV TLS DN components failed with error code "
                    + errorCode.getInternalErrorCode());
        }
        // Verify that the response is of the right type
        assertNotNull(certificateResponse);
        assertTrue(certificateResponse.getResponseType().equals(CertificateHelper.RESPONSETYPE_CERTIFICATE));
        // Verify that the certificate in the response has the same Subject DN
        // as in the request.
        cert = certificateResponse.getCertificate();
        assertNotNull(cert);
        assertEquals(
                "JurisdictionCountry=DE,JurisdictionState=Stockholm,JurisdictionLocality=Solna,CN=EVTLSEJBCAWSTEST",
                CertTools.getSubjectDN(cert));
    } finally {
        // Clean up immediately
        endEntityManagementSession.deleteUser(admin, "EVTLSEJBCAWSTEST");
        internalCertStoreSession.removeCertificate(CertTools.getFingerprintAsString(cert));
    }
}

From source file:org.viafirma.nucleo.validacion.CRLValidationHandler.java

/**
 * Metodo encargado de la verificacin de los certificados
 * //w  w  w. ja v a2  s .c  om
 * @param certificadoX509
 * @throws ExcepcionErrorInterno
 */
public CodigoError validarCRL(X509Certificate certificadoX509) {

    try {
        // 1.- Inicia la factoria de certificados
        CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        log.debug("Validando certificado perteneciente a: " + certificadoX509.getIssuerDN());
        CertPathValidator validador = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);

        // 2.- Configuracin de los parametros del validador
        // 2.1.- Para comprobar que el camino de confianza no esta roto,
        // tengo en cuenta todos los certificados
        PKIXParameters parametros = new PKIXParameters(certificadosConfianza);
        // Fecha para la comprobacin de validez.
        parametros.setDate(new Date());

        if (validacionOnline) {
            // Para la validacin online de del estado de revocacin de los
            // certificados

            // ************
            // creo un almacen( cache ) de certificados y CRLs para no tener
            // que conectarme a las crls
            // en cada validacin

            // Genero un listado de las CRLS que vamos a utilizar para la
            // validacin del certificado.
            List<CRL> listaCRLsCertificadosAlmacenados = new LinkedList<CRL>();

            // Aade las crls de los certificados de confianza reconocidos
            // por Viafirma.
            // estos certificados son los marcados con el prefijo viafirma_
            for (TrustAnchor trustAnchor : certificadosConfianza) {
                // TODO establecer un sistema de cache eficiente
                // TODO recuperar solo las crls del certificado en uso.
                listaCRLsCertificadosAlmacenados
                        .addAll(CRLUtil.getCurrentInstance().getCRLs(trustAnchor.getTrustedCert()));
                // para cada certificado.
            }

            // aado al listado todas las crls del certificado actual. EJ
            // para el caso de
            // un certificado de FNMT el certificado personal contiene CN =
            // CRL1827,OU = FNMT Clase 2 CA,O = FNMT,C = ES
            listaCRLsCertificadosAlmacenados.addAll(CRLUtil.getCurrentInstance().getCRLs(certificadoX509));

            // parametros para la creacin del almacen(cache CRLs)
            CollectionCertStoreParameters params = new CollectionCertStoreParameters(
                    listaCRLsCertificadosAlmacenados);
            CertStore almacen = CertStore.getInstance("Collection", params, BouncyCastleProvider.PROVIDER_NAME);

            parametros.addCertStore(almacen);
        } else {
            // No se utilizan las CRLs para la comprobacin de la
            // revocacin.
            parametros.setRevocationEnabled(false);
        }

        // certificados a validar ( solo 1)
        List<X509Certificate> certificadosValidar = new ArrayList<X509Certificate>(1);
        certificadosValidar.add(certificadoX509);

        // genero el listado de certificados a validar
        CertPath certPath = factoriaCertificados.generateCertPath(certificadosValidar);
        // validacin
        CertPathValidatorResult resultado = validador.validate(certPath, parametros);
        if (log.isDebugEnabled()) {
            if (resultado instanceof java.security.cert.PKIXCertPathValidatorResult) {
                // pintamos el arbol de politicas
                PolicyNode node = ((java.security.cert.PKIXCertPathValidatorResult) resultado).getPolicyTree();
                StringBuffer ruta = new StringBuffer(
                        "Certificado vlido: " + certificadoX509.getSubjectDN().getName());
                while (node != null) {
                    ruta.append("-->");
                    ruta.append(node.getValidPolicy());
                    if (node.getChildren().hasNext()) {
                        node = node.getChildren().next();
                    } else {
                        node = null;
                    }
                }
                log.info("ruta de validacin: " + ruta);
            }
        }
        return CodigoError.OK_CERTIFICADO_VALIDADO;
    } catch (CertificateException e) {
        log.fatal(CodigoError.ERROR_INTERNO, e);
        return CodigoError.ERROR_INTERNO;
    } catch (NoSuchProviderException e) {
        log.fatal(CodigoError.ERROR_INTERNO, e);
        return CodigoError.ERROR_INTERNO;

    } catch (NoSuchAlgorithmException e) {
        log.fatal(CodigoError.ERROR_INTERNO, e);
        return CodigoError.ERROR_INTERNO;
    } catch (InvalidAlgorithmParameterException e) {
        log.fatal(CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO, e);
        return CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO;
    } catch (CRLException e) {
        log.fatal(CodigoError.ERROR_VALIDACION_CRL, e);
        return CodigoError.ERROR_VALIDACION_CRL;
    } catch (CertPathValidatorException e) {
        // detectamos el tipo de problema
        if (e.getMessage().contains(java.security.cert.CertificateExpiredException.class.getName())
                || e.getMessage().contains("Certificate revocation after")
                || e.getMessage().contains("NotAfter") || e.getMessage().contains("certificate expired on")) {
            log.warn("El certificado esta caducado." + e.getMessage() + " " + certificadoX509.getSubjectDN());
            return CodigoError.ERROR_VALIDACION_CERTIFICADO_CADUCADO;
        } else if (e.getMessage().contains(java.security.SignatureException.class.getName())) {
            log.warn(
                    "Algunos de los certificados en el camino de certificacin no tiene crl. Algunos de los certificados no se puede validar."
                            + e.getMessage() + " " + certificadoX509.getSubjectDN());
            return CodigoError.ERROR_VALIDACION_CRL;
        } else if (e.getMessage().contains("no valid CRL found")) {
            log.warn("No se ha podido comprobar la validez del certificado. " + e.getMessage() + " "
                    + certificadoX509.getSubjectDN());
            return CodigoError.ERROR_VALIDACION_CRL;
        } else if (e.getMessage().contains("CertPath not found")) {
            log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " "
                    + certificadoX509.getIssuerDN());
            return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA;
        } else {
            log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " "
                    + certificadoX509.getIssuerDN());
            return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA;
        }

        // TODO java.security.cert.CertPathValidatorException: couldn't
        // validate certificate:
        // java.security.cert.CertificateNotYetValidException: NotBefore:
        // Thu Apr 19 19:22:17 CEST 2007
        // at
        // org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi.engineValidate(PKIXCertPathValidatorSpi.java:819)

    }
}