Example usage for org.bouncycastle.asn1.pkcs CertificationRequestInfo getSubjectPublicKeyInfo

List of usage examples for org.bouncycastle.asn1.pkcs CertificationRequestInfo getSubjectPublicKeyInfo

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs CertificationRequestInfo getSubjectPublicKeyInfo.

Prototype

public SubjectPublicKeyInfo getSubjectPublicKeyInfo() 

Source Link

Usage

From source file:org.glite.slcs.caclient.impl.CMPRequest.java

License:eu-egee.org license

private static CertTemplate makeCertTemplate(CertificateRequest certRequest, String issuerDN) {
    PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(certRequest.getDEREncoded());
    CertificationRequestInfo pkcs10info = pkcs10.getCertificationRequestInfo();

    log.debug("Constructing CMP CertTemplate...");
    CertTemplate certTemplate = new CertTemplate();
    certTemplate.setPublicKey(pkcs10info.getSubjectPublicKeyInfo());
    certTemplate.setSubject(pkcs10info.getSubject());
    certTemplate.setIssuer(new X509Name(issuerDN));

    // validity//from   w  w w.  ja va 2s .c  o m
    OptionalValidity validity = new OptionalValidity();
    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    // five minutes extra to before/after
    date.add(Calendar.MINUTE, -5);
    Time notBefore = new Time(date.getTime());
    date.add(Calendar.MINUTE, 5);
    // TODO: lifetime fixed to 1 mio seconds, should be possible to configure by user
    date.add(Calendar.SECOND, 1000000);
    Time notAfter = new Time(date.getTime());
    validity.setNotBefore(notBefore);
    validity.setNotAfter(notAfter);
    certTemplate.setValidity(validity);

    log.debug("Constructed " + certTemplate.toString());

    return certTemplate;
}

From source file:org.xipki.ca.server.impl.CAManagerImpl.java

License:Open Source License

@Override
public X509Certificate generateCertificate(final String caName, final String profileName, final String user,
        final byte[] encodedPkcs10Request) throws CAMgmtException {
    ParamChecker.assertNotBlank("caName", caName);
    ParamChecker.assertNotBlank("profileName", profileName);
    ParamChecker.assertNotNull("encodedPkcs10Request", encodedPkcs10Request);

    X509CA ca = getX509CA(caName);//  ww w  . jav a  2  s . c o  m
    CertificationRequest p10cr;
    try {
        p10cr = CertificationRequest.getInstance(encodedPkcs10Request);
    } catch (Exception e) {
        throw new CAMgmtException("invalid PKCS#10 request. ERROR: " + e.getMessage());
    }

    if (securityFactory.verifyPOPO(p10cr) == false) {
        throw new CAMgmtException("could not validate POP for the pkcs#10 requst");
    }

    CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
    Extensions extensions = null;
    ASN1Set attrs = certTemp.getAttributes();
    for (int i = 0; i < attrs.size(); i++) {
        Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
        if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
            extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
        }
    }

    X500Name subject = certTemp.getSubject();
    SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();

    X509CertificateInfo certInfo;
    try {
        certInfo = ca.generateCertificate(false, null, profileName, user, subject, publicKeyInfo, null, null,
                extensions);
    } catch (OperationException e) {
        throw new CAMgmtException(e.getMessage(), e);
    }

    return certInfo.getCert().getCert();
}

From source file:org.xipki.ca.server.impl.X509CACmpResponder.java

License:Open Source License

/**
 * handle the PKI body with the choice {@code p10cr}<br/>
 * Since it is not possible to add attribute to the PKCS#10 request, the certificate profile
 * must be specified in the attribute regInfo-utf8Pairs (1.3.6.1.5.5.7.5.2.1) within
 * PKIHeader.generalInfo/*from  ww  w . ja  v  a 2s .c  om*/
 *
 */
private PKIBody processP10cr(final CmpRequestorInfo requestor, final String user, final ASN1OctetString tid,
        final PKIHeader reqHeader, final CertificationRequest p10cr, final long confirmWaitTime,
        final boolean sendCaCert, final AuditEvent auditEvent) throws InsuffientPermissionException {
    // verify the POP first
    CertResponse certResp;
    ASN1Integer certReqId = new ASN1Integer(-1);

    AuditChildEvent childAuditEvent = null;
    if (auditEvent != null) {
        childAuditEvent = new AuditChildEvent();
        auditEvent.addChildAuditEvent(childAuditEvent);
    }

    if (securityFactory.verifyPOPO(p10cr) == false) {
        LOG.warn("could not validate POP for the pkcs#10 requst");
        PKIStatusInfo status = generateCmpRejectionStatus(PKIFailureInfo.badPOP, null);
        certResp = new CertResponse(certReqId, status);
        if (childAuditEvent != null) {
            childAuditEvent.setStatus(AuditStatus.FAILED);
            childAuditEvent.addEventData(new AuditEventData("message", "invalid POP"));
        }
    } else {
        CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
        Extensions extensions = null;
        ASN1Set attrs = certTemp.getAttributes();
        for (int i = 0; i < attrs.size(); i++) {
            Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
            if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
                extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
            }
        }

        X500Name subject = certTemp.getSubject();
        if (childAuditEvent != null) {
            childAuditEvent.addEventData(new AuditEventData("subject", X509Util.getRFC4519Name(subject)));
        }

        SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();

        try {
            CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
            String certprofileName = keyvalues == null ? null
                    : keyvalues.getValue(CmpUtf8Pairs.KEY_CERT_PROFILE);
            if (certprofileName == null) {
                throw new CMPException("no certificate profile is specified");
            }

            if (childAuditEvent != null) {
                childAuditEvent.addEventData(new AuditEventData("certprofile", certprofileName));
            }

            checkPermission(requestor, certprofileName);

            certResp = generateCertificate(requestor, user, tid, certReqId, subject, publicKeyInfo, null,
                    extensions, certprofileName, false, confirmWaitTime, childAuditEvent);
        } catch (CMPException e) {
            certResp = new CertResponse(certReqId,
                    generateCmpRejectionStatus(PKIFailureInfo.badCertTemplate, e.getMessage()));
            if (childAuditEvent != null) {
                childAuditEvent.setStatus(AuditStatus.FAILED);
                childAuditEvent.addEventData(new AuditEventData("message", "badCertTemplate"));
            }
        } // end try
    }

    CMPCertificate[] caPubs = sendCaCert ? new CMPCertificate[] { getCA().getCAInfo().getCertInCMPFormat() }
            : null;
    CertRepMessage repMessage = new CertRepMessage(caPubs, new CertResponse[] { certResp });

    return new PKIBody(PKIBody.TYPE_CERT_REP, repMessage);
}

From source file:org.xipki.pki.ca.qa.shell.CheckCertCmd.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    Set<String> issuerNames = qaSystemManager.getIssuerNames();
    if (isEmpty(issuerNames)) {
        throw new IllegalCmdParamException("no issuer is configured");
    }/*ww w  . jav a  2  s.c o  m*/

    if (issuerName == null) {
        if (issuerNames.size() != 1) {
            throw new IllegalCmdParamException("no issuer is specified");
        }

        issuerName = issuerNames.iterator().next();
    }

    if (!issuerNames.contains(issuerName)) {
        throw new IllegalCmdParamException(
                "issuer " + issuerName + " is not within the configured issuers " + issuerNames);
    }

    X509IssuerInfo issuerInfo = qaSystemManager.getIssuer(issuerName);

    X509CertprofileQa qa = qaSystemManager.getCertprofile(profileName);
    if (qa == null) {
        throw new IllegalCmdParamException("found no certificate profile named '" + profileName + "'");
    }

    CertificationRequest csr = CertificationRequest.getInstance(IoUtil.read(csrFile));
    Extensions extensions = null;
    CertificationRequestInfo reqInfo = csr.getCertificationRequestInfo();
    ASN1Set attrs = reqInfo.getAttributes();
    for (int i = 0; i < attrs.size(); i++) {
        Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
        if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
            extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
        }
    }

    byte[] certBytes = IoUtil.read(certFile);
    ValidationResult result = qa.checkCert(certBytes, issuerInfo, reqInfo.getSubject(),
            reqInfo.getSubjectPublicKeyInfo(), extensions);
    StringBuilder sb = new StringBuilder();

    sb.append(certFile).append(" (certprofile ").append(profileName).append(")\n");
    sb.append("\tcertificate is ");
    sb.append(result.isAllSuccessful() ? "valid" : "invalid");

    if (verbose.booleanValue()) {
        for (ValidationIssue issue : result.getValidationIssues()) {
            sb.append("\n");
            format(issue, "    ", sb);
        }
    }

    println(sb.toString());
    if (!result.isAllSuccessful()) {
        throw new CmdFailure("certificate is invalid");
    }
    return null;
}

From source file:org.xipki.pki.ca.server.impl.CaManagerImpl.java

License:Open Source License

@Override
public X509Certificate generateCertificate(final String caName, final String profileName, final String user,
        final byte[] encodedCsr, Date notBefore, Date notAfter) throws CaMgmtException {
    ParamUtil.requireNonBlank("caName", caName);
    ParamUtil.requireNonBlank("profileName", profileName);
    ParamUtil.requireNonNull("encodedCsr", encodedCsr);

    AuditEvent event = new AuditEvent(new Date());
    event.setApplicationName(CaAuditConstants.APPNAME);
    event.setName(CaAuditConstants.NAME_PERF);
    event.addEventType("CAMGMT_CRL_GEN_ONDEMAND");

    X509Ca ca = getX509Ca(caName);//from   w w  w.  j  a v a2  s  .  c o  m
    CertificationRequest csr;
    try {
        csr = CertificationRequest.getInstance(encodedCsr);
    } catch (Exception ex) {
        throw new CaMgmtException("invalid CSR request. ERROR: " + ex.getMessage());
    }

    CmpControl cmpControl = getCmpControlObject(ca.getCaInfo().getCmpControlName());
    if (!securityFactory.verifyPopo(csr, cmpControl.getPopoAlgoValidator())) {
        throw new CaMgmtException("could not validate POP for the CSR");
    }

    CertificationRequestInfo certTemp = csr.getCertificationRequestInfo();
    Extensions extensions = null;
    ASN1Set attrs = certTemp.getAttributes();
    for (int i = 0; i < attrs.size(); i++) {
        Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
        if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
            extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
        }
    }

    X500Name subject = certTemp.getSubject();
    SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();

    CertTemplateData certTemplateData = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter,
            extensions, profileName);

    X509CertificateInfo certInfo;
    try {
        certInfo = ca.generateCertificate(certTemplateData, false, null, user, RequestType.CA, (byte[]) null,
                CaAuditConstants.MSGID_CA_mgmt);
    } catch (OperationException ex) {
        throw new CaMgmtException(ex.getMessage(), ex);
    }

    if (ca.getCaInfo().isSaveRequest()) {
        try {
            long dbId = ca.addRequest(encodedCsr);
            ca.addRequestCert(dbId, certInfo.getCert().getCertId());
        } catch (OperationException ex) {
            LogUtil.warn(LOG, ex, "could not save request");
        }
    }

    return certInfo.getCert().getCert();
}

From source file:org.xipki.pki.ca.server.impl.cmp.X509CaCmpResponder.java

License:Open Source License

/**
 * handle the PKI body with the choice {@code p10cr}<br/>
 * Since it is not possible to add attribute to the PKCS#10 request (CSR), the certificate
 * profile must be specified in the attribute regInfo-utf8Pairs (1.3.6.1.5.5.7.5.2.1) within
 * PKIHeader.generalInfo/*from   w w w  .  j a  va  2  s .  c o  m*/
 *
 */
private PKIBody processP10cr(final PKIMessage request, final CmpRequestorInfo requestor, final String user,
        final ASN1OctetString tid, final PKIHeader reqHeader, final CertificationRequest p10cr,
        final CmpControl cmpControl, final String msgId, final AuditEvent event) {
    // verify the POP first
    CertResponse certResp;
    ASN1Integer certReqId = new ASN1Integer(-1);

    boolean certGenerated = false;
    X509Ca ca = getCa();

    if (!securityFactory.verifyPopo(p10cr, getCmpControl().getPopoAlgoValidator())) {
        LOG.warn("could not validate POP for the pkcs#10 requst");
        certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badPOP, "invalid POP");
    } else {
        CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
        Extensions extensions = CaUtil.getExtensions(certTemp);

        X500Name subject = certTemp.getSubject();
        SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();

        CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
        String certprofileName = null;
        Date notBefore = null;
        Date notAfter = null;

        if (keyvalues != null) {
            certprofileName = keyvalues.getValue(CmpUtf8Pairs.KEY_CERT_PROFILE);

            String str = keyvalues.getValue(CmpUtf8Pairs.KEY_NOT_BEFORE);
            if (str != null) {
                notBefore = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
            }

            str = keyvalues.getValue(CmpUtf8Pairs.KEY_NOT_AFTER);
            if (str != null) {
                notAfter = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
            }
        }

        if (certprofileName == null) {
            certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badCertTemplate, "badCertTemplate",
                    null);
        } else {
            if (!isCertProfilePermitted(requestor, certprofileName)) {
                String msg = "certprofile " + certprofileName + " is not allowed";
                certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.notAuthorized, msg);
            } else {
                CertTemplateData certTemplateData = new CertTemplateData(subject, publicKeyInfo, notBefore,
                        notAfter, extensions, certprofileName);

                certResp = generateCertificates(Arrays.asList(certTemplateData), Arrays.asList(certReqId),
                        requestor, user, tid, false, request, cmpControl, msgId, event).get(0);
                certGenerated = true;
            }
        }
    }

    CMPCertificate[] caPubs = null;
    if (certGenerated && cmpControl.isSendCaCert()) {
        caPubs = new CMPCertificate[] { ca.getCaInfo().getCertInCmpFormat() };
    }
    CertRepMessage repMessage = new CertRepMessage(caPubs, new CertResponse[] { certResp });

    return new PKIBody(PKIBody.TYPE_CERT_REP, repMessage);
}

From source file:org.xipki.pki.ca.server.impl.cmp.X509CaCmpResponder.java

License:Open Source License

/**
 * @since 2.1.0://  www.  j a  v  a 2s  .  co  m
 */
public X509Cert generateCert(final CmpRequestorInfo requestor, final byte[] encodedCsr,
        final String profileName, final Date notBefore, final Date notAfter, final String user,
        final RequestType reqType, final String msgId) throws OperationException {
    ParamUtil.requireNonNull("requestor", requestor);
    try {
        checkPermission(requestor, Permission.ENROLL_CERT);
    } catch (InsuffientPermissionException ex) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
    }

    CertificationRequest csr = CertificationRequest.getInstance(encodedCsr);
    if (!securityFactory.verifyPopo(csr, getCmpControl().getPopoAlgoValidator())) {
        LOG.warn("could not validate POP for the pkcs#10 requst");
        throw new OperationException(ErrorCode.BAD_POP);
    }

    CertificationRequestInfo certTemp = csr.getCertificationRequestInfo();

    X500Name subject = certTemp.getSubject();
    SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();

    if (!isCertProfilePermitted(requestor, profileName)) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "certProfile " + profileName + " is not allowed");
    }

    Extensions extensions = CaUtil.getExtensions(certTemp);
    CertTemplateData certTemplate = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter,
            extensions, profileName);

    X509Ca ca = getCa();
    X509CertificateInfo certInfo = ca.generateCertificate(certTemplate, requestor.isRa(), requestor, user,
            reqType, null, msgId);
    certInfo.setRequestor(requestor);
    certInfo.setUser(user);

    if (ca.getCaInfo().isSaveRequest()) {
        long dbId = ca.addRequest(encodedCsr);
        ca.addRequestCert(dbId, certInfo.getCert().getCertId());
    }

    return certInfo.getCert();
}

From source file:org.xipki.pki.ca.server.impl.scep.Scep.java

License:Open Source License

private PkiMessage doServicePkiOperation(final CMSSignedData requestContent, final DecodedPkiMessage req,
        final String certProfileName, final String msgId, final AuditEvent event)
        throws MessageDecodingException, OperationException {
    ParamUtil.requireNonNull("requestContent", requestContent);
    ParamUtil.requireNonNull("req", req);

    String tid = req.getTransactionId().getId();
    // verify and decrypt the request
    audit(event, CaAuditConstants.NAME_tid, tid);
    if (req.getFailureMessage() != null) {
        audit(event, CaAuditConstants.NAME_SCEP_failureMessage, req.getFailureMessage());
    }/*w ww.j  av a 2s . com*/
    Boolean bo = req.isSignatureValid();
    if (bo != null && !bo.booleanValue()) {
        audit(event, CaAuditConstants.NAME_SCEP_signature, "invalid");
    }
    bo = req.isDecryptionSuccessful();
    if (bo != null && !bo.booleanValue()) {
        audit(event, CaAuditConstants.NAME_SCEP_decryption, "failed");
    }

    PkiMessage rep = new PkiMessage(req.getTransactionId(), MessageType.CertRep, Nonce.randomNonce());
    rep.setRecipientNonce(req.getSenderNonce());

    if (req.getFailureMessage() != null) {
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badRequest);
    }

    bo = req.isSignatureValid();
    if (bo != null && !bo.booleanValue()) {
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badMessageCheck);
    }

    bo = req.isDecryptionSuccessful();
    if (bo != null && !bo.booleanValue()) {
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badRequest);
    }

    Date signingTime = req.getSigningTime();
    if (maxSigningTimeBiasInMs > 0) {
        boolean isTimeBad = false;
        if (signingTime == null) {
            isTimeBad = true;
        } else {
            long now = System.currentTimeMillis();
            long diff = now - signingTime.getTime();
            if (diff < 0) {
                diff = -1 * diff;
            }
            isTimeBad = diff > maxSigningTimeBiasInMs;
        }

        if (isTimeBad) {
            rep.setPkiStatus(PkiStatus.FAILURE);
            rep.setFailInfo(FailInfo.badTime);
        }
    } // end if

    // check the digest algorithm
    String oid = req.getDigestAlgorithm().getId();
    ScepHashAlgoType hashAlgoType = ScepHashAlgoType.forNameOrOid(oid);
    if (hashAlgoType == null) {
        LOG.warn("tid={}: unknown digest algorithm {}", tid, oid);
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badAlg);
    } else {
        boolean supported = false;
        if (hashAlgoType == ScepHashAlgoType.SHA1) {
            if (caCaps.containsCapability(CaCapability.SHA1)) {
                supported = true;
            }
        } else if (hashAlgoType == ScepHashAlgoType.SHA256) {
            if (caCaps.containsCapability(CaCapability.SHA256)) {
                supported = true;
            }
        } else if (hashAlgoType == ScepHashAlgoType.SHA512) {
            if (caCaps.containsCapability(CaCapability.SHA512)) {
                supported = true;
            }
        }

        if (!supported) {
            LOG.warn("tid={}: unsupported digest algorithm {}", tid, oid);
            rep.setPkiStatus(PkiStatus.FAILURE);
            rep.setFailInfo(FailInfo.badAlg);
        }
    }

    // check the content encryption algorithm
    ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
    if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
        if (!caCaps.containsCapability(CaCapability.DES3)) {
            LOG.warn("tid={}: encryption with DES3 algorithm is not permitted", tid, encOid);
            rep.setPkiStatus(PkiStatus.FAILURE);
            rep.setFailInfo(FailInfo.badAlg);
        }
    } else if (AES_ENC_ALGOS.contains(encOid)) {
        if (!caCaps.containsCapability(CaCapability.AES)) {
            LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
            rep.setPkiStatus(PkiStatus.FAILURE);
            rep.setFailInfo(FailInfo.badAlg);
        }
    } else {
        LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(FailInfo.badAlg);
    }

    if (rep.getPkiStatus() == PkiStatus.FAILURE) {
        return rep;
    }

    X509Ca ca;
    try {
        ca = caManager.getX509Ca(caName);
    } catch (CaMgmtException ex) {
        LogUtil.error(LOG, ex, tid + "=" + tid + ",could not get X509CA");
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
    }

    X500Name caX500Name = ca.getCaInfo().getCertificate().getSubjectAsX500Name();

    try {
        SignedData signedData;

        MessageType mt = req.getMessageType();
        audit(event, CaAuditConstants.NAME_SCEP_messageType, mt.toString());

        switch (mt) {
        case PKCSReq:
        case RenewalReq:
        case UpdateReq:
            CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
            X500Name reqSubject = csr.getCertificationRequestInfo().getSubject();
            String reqSubjectText = X509Util.getRfc4519Name(reqSubject);
            LOG.info("tid={}, subject={}", tid, reqSubjectText);

            CmpControl cmpControl = caManager.getCmpControlObject(ca.getCaInfo().getCmpControlName());
            if (!caManager.getSecurityFactory().verifyPopo(csr, cmpControl.getPopoAlgoValidator())) {
                LOG.warn("tid={}, POPO verification failed", tid);
                throw FailInfoException.BAD_MESSAGE_CHECK;
            }

            CertificationRequestInfo csrReqInfo = csr.getCertificationRequestInfo();
            X509Certificate reqSignatureCert = req.getSignatureCert();
            boolean selfSigned = reqSignatureCert.getSubjectX500Principal()
                    .equals(reqSignatureCert.getIssuerX500Principal());

            String cn = X509Util.getCommonName(csrReqInfo.getSubject());
            if (cn == null) {
                throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE,
                        "tid=" + tid + ": no CommonName in requested subject");
            }

            String user = null;
            boolean authenticatedByPwd = false;

            String challengePwd = CaUtil.getChallengePassword(csrReqInfo);
            if (challengePwd != null) {
                String[] strs = challengePwd.split(":");
                if (strs != null && strs.length == 2) {
                    user = strs[0];
                    String password = strs[1];
                    authenticatedByPwd = ca.authenticateUser(user, password.getBytes());

                    if (!authenticatedByPwd) {
                        LOG.warn("tid={}: could not verify the challengePassword", tid);
                        throw FailInfoException.BAD_REQUEST;
                    }
                } else {
                    LOG.warn("tid={}: ignore challengePassword since it does not has the"
                            + " format <user>:<password>", tid);
                }
            } // end if

            if (selfSigned) {
                if (MessageType.PKCSReq != mt) {
                    LOG.warn("tid={}: self-signed certificate is not permitted for" + " messageType {}", tid,
                            mt);
                    throw FailInfoException.BAD_REQUEST;
                }
                if (user == null) {
                    LOG.warn("tid={}: could not extract user & password from challengePassword"
                            + ", which are required for self-signed signature certificate", tid);
                    throw FailInfoException.BAD_REQUEST;
                }
                checkCommonName(ca, user, cn);
            } else {
                if (user == null) {
                    // up to draft-nourse-scep-23 the client sends all messages to enroll
                    // certificate via MessageType PKCSReq
                    KnowCertResult knowCertRes = ca.knowsCertificate(reqSignatureCert);
                    if (!knowCertRes.isKnown()) {
                        LOG.warn("tid={}: signature certificate is not trusted by the CA", tid);
                        throw FailInfoException.BAD_REQUEST;
                    }
                    user = knowCertRes.getUser();
                } // end if

                // only the same subject is permitted
                String cnInSignatureCert = X509Util.getCommonName(
                        X500Name.getInstance(reqSignatureCert.getSubjectX500Principal().getEncoded()));
                boolean b2 = cn.equals(cnInSignatureCert);
                if (!b2) {
                    if (user != null) {
                        checkCommonName(ca, user, cn);
                    } else {
                        LOG.warn("tid={}: signature certificate is not trusted and {}", tid,
                                "no challengePassword is contained in the request");
                        throw FailInfoException.BAD_REQUEST;
                    }
                } // end if
            } // end if

            byte[] tidBytes = getTransactionIdBytes(tid);

            Extensions extensions = CaUtil.getExtensions(csrReqInfo);
            CertTemplateData certTemplateData = new CertTemplateData(csrReqInfo.getSubject(),
                    csrReqInfo.getSubjectPublicKeyInfo(), (Date) null, (Date) null, extensions,
                    certProfileName);
            X509CertificateInfo cert = ca.generateCertificate(certTemplateData, true, null, user,
                    RequestType.SCEP, tidBytes, msgId);
            /* Don't save SCEP message, since it contains password in plaintext
            if (ca.getCaInfo().isSaveRequest() && cert.getCert().getCertId() != null) {
            byte[] encodedRequest;
            try {
                encodedRequest = requestContent.getEncoded();
            } catch (IOException ex) {
                LOG.warn("could not encode request");
                encodedRequest = null;
            }
            if (encodedRequest != null) {
                long reqId = ca.addRequest(encodedRequest);
                ca.addRequestCert(reqId, cert.getCert().getCertId());
            }
            }*/

            signedData = buildSignedData(cert.getCert().getCert());
            break;
        case CertPoll:
            IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
            audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(is.getIssuer()));
            audit(event, CaAuditConstants.NAME_subject, X509Util.getRfc4519Name(is.getSubject()));

            ensureIssuedByThisCa(caX500Name, is.getIssuer());
            signedData = pollCert(ca, is.getSubject(), req.getTransactionId());
            break;
        case GetCert:
            IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            BigInteger serial = isn.getSerialNumber().getPositiveValue();
            audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
            audit(event, CaAuditConstants.NAME_serial, LogUtil.formatCsn(serial));
            ensureIssuedByThisCa(caX500Name, isn.getName());
            signedData = getCert(ca, isn.getSerialNumber().getPositiveValue());
            break;
        case GetCRL:
            isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            serial = isn.getSerialNumber().getPositiveValue();
            audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
            audit(event, CaAuditConstants.NAME_serial, LogUtil.formatCsn(serial));
            ensureIssuedByThisCa(caX500Name, isn.getName());
            signedData = getCrl(ca, serial);
            break;
        default:
            LOG.error("unknown SCEP messageType '{}'", req.getMessageType());
            throw FailInfoException.BAD_REQUEST;
        } // end switch

        ContentInfo ci = new ContentInfo(CMSObjectIdentifiers.signedData, signedData);
        rep.setMessageData(ci);
        rep.setPkiStatus(PkiStatus.SUCCESS);
    } catch (FailInfoException ex) {
        LogUtil.error(LOG, ex);
        rep.setPkiStatus(PkiStatus.FAILURE);
        rep.setFailInfo(ex.getFailInfo());
    }

    return rep;
}

From source file:org.xipki.pki.scep.serveremulator.CaEmulator.java

License:Open Source License

public Certificate generateCert(final CertificationRequest csr) throws Exception {
    if (!verifyPopo(csr)) {
        throw new Exception("CSR invalid");
    }/*from w ww.j  a v a2s  .  c  o  m*/
    CertificationRequestInfo reqInfo = csr.getCertificationRequestInfo();
    return generateCert(reqInfo.getSubjectPublicKeyInfo(), reqInfo.getSubject());
}