Search in sources :

Example 11 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class ScepClientExample method main.

public static void main(String[] args) {
    try {
        X509Cert caCert = X509Util.parseCert(IoUtil.read(new FileInputStream(expandPath(CA_CERT_FILE))));
        CaIdentifier tmpCaId = new CaIdentifier(CA_URL, null);
        CaCertValidator caCertValidator = new CaCertValidator.PreprovisionedCaCertValidator(caCert);
        ScepClient client = new ScepClient(tmpCaId, caCertValidator);
        client.init();
        // Self-Signed Identity Certificate
        MyKeypair keypair = generateRsaKeypair();
        CertificationRequest csr = genCsr(keypair, getSubject(), challengePassword);
        // self-signed cert must use the same subject as in CSR
        X500Name subjectDn = csr.getCertificationRequestInfo().getSubject();
        X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn, BigInteger.valueOf(1), new Date(), new Date(System.currentTimeMillis() + 24 * 3600 * 1000), subjectDn, keypair.getPublic());
        ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keypair.getPrivate());
        X509Cert selfSignedCert = new X509Cert(certGenerator.build(signer));
        // Enroll certificate - RSA
        EnrolmentResponse resp = client.scepEnrol(csr, keypair.getPrivate(), selfSignedCert);
        if (resp.isFailure()) {
            throw new Exception("server returned 'failure'");
        }
        if (resp.isPending()) {
            throw new Exception("server returned 'pending'");
        }
        X509Cert cert = resp.getCertificates().get(0);
        printCert("SCEP (RSA, Self-Signed Identity Cert)", cert);
        // Use the CA signed identity certificate
        X509Cert identityCert = cert;
        PrivateKey identityKey = keypair.getPrivate();
        keypair = generateRsaKeypair();
        csr = genCsr(keypair, getSubject(), challengePassword);
        // Enroll certificate - RSA
        resp = client.scepEnrol(csr, identityKey, identityCert);
        if (resp.isFailure()) {
            throw new Exception("server returned 'failure'");
        }
        if (resp.isPending()) {
            throw new Exception("server returned 'pending'");
        }
        cert = resp.getCertificates().get(0);
        printCert("SCEP (RSA, CA issued identity Cert)", cert);
        client.destroy();
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(-1);
    }
}
Also used : PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CaIdentifier(org.xipki.scep.client.CaIdentifier) ContentSigner(org.bouncycastle.operator.ContentSigner) ScepClient(org.xipki.scep.client.ScepClient) X500Name(org.bouncycastle.asn1.x500.X500Name) FileInputStream(java.io.FileInputStream) Date(java.util.Date) CaCertValidator(org.xipki.scep.client.CaCertValidator) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509Cert(org.xipki.security.X509Cert) EnrolmentResponse(org.xipki.scep.client.EnrolmentResponse) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 12 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project portal by ixinportal.

the class CertServiceTest method test.

// @Test
public void test() {
    // String url = "http://124.205.224.179:9018/portal/cert/make";
    String url = "http://127.0.0.1:8080/portal/cert/make";
    String csr = "MIIBbjCB2AIBADAvMQ0wCwYDVQQDDAR5dXlpMQ4wDAYDVQQLDAVpdHJ1czEOMAwGA1UECgwFQ2hpbmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMGP9RCdWGpTUO8N0Nf5R9hc2SXMqGEJ4o0ler7IzEmSlGkc4MloO9XGwvrAyznlibeuhpjIoCZtoX7oTasqeMko2eMK7ILgzlamBfbZtZlhE3pyw+PmNNU9lQqzWkoIAdv7tnWaDULOsLNOTCWX/cXA1Psd7FZ1GSW6IY3UX0NhAgMBAAGgADANBgkqhkiG9w0BAQUFAAOBgQCwt1fNaXIUPP+BlziXeVE01IqqaNyC3NX7hvSZ0e1t3cHBI01j/IO5qQslXhd3yF8u07lN4SIqGWR9tWc4eo65COMEf9tWOXC/VHQCovRc3NZ+LrWDxi2ay1SEoLJ04KlqQBXeuzaoFId2TkbHRrQrsjqN+BedejUv6iflquPsSw==";
    String billId = "TWCX20171226144336740340";
    // String uid = null;
    // userId = null;
    byte[] reqder = Base64.decode(csr);
    // 分解原证书请求
    CertificationRequest creq = CertificationRequest.getInstance(reqder);
    System.out.println(creq.getSignature());
    System.out.println(creq.getDEREncoded());
    System.out.println(creq.getDERObject());
    System.out.println(creq.getSignatureAlgorithm().getAlgorithm());
    System.out.println("******************************************************************");
    System.out.println(creq.getCertificationRequestInfo().getAttributes());
    System.out.println(creq.getCertificationRequestInfo().getSubject());
    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
    map.add("csr", csr);
    map.add("billId", billId);
    // map.add("delayDays", 10);
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.add("authHmac", Base64.encode(HMACSHA1.getHmacSHA1(csr + billId, /*+uid+userId*/
        "eaf3ce8373d34b4eba47173d1febc507"), false));
        System.out.println(Base64.encode(HMACSHA1.getHmacSHA1(csr + billId, /*+uid+userId*/
        "eaf3ce8373d34b4eba47173d1febc507"), false));
        HttpEntity httpEntity = new HttpEntity(map, headers);
        ResponseEntity<String> resStr = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        System.out.println("statusCode:" + resStr.getStatusCode());
        System.out.println("body:" + resStr.getBody());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) JSONObject(com.alibaba.fastjson.JSONObject) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 13 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class CaManagerImpl method generateCertificate.

// method removeCertificate
@Override
public X509Certificate generateCertificate(String caName, String profileName, byte[] encodedCsr, Date notBefore, Date notAfter) throws CaMgmtException {
    caName = ParamUtil.requireNonBlank("caName", caName).toLowerCase();
    profileName = ParamUtil.requireNonBlank("profileName", profileName).toLowerCase();
    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);
    CertificationRequest csr;
    try {
        csr = CertificationRequest.getInstance(encodedCsr);
    } catch (Exception ex) {
        throw new CaMgmtException(concat("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, byCaRequestor, 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();
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) Attribute(org.bouncycastle.asn1.pkcs.Attribute) X509CertificateInfo(org.xipki.ca.api.publisher.x509.X509CertificateInfo) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) CertprofileException(org.xipki.ca.api.profile.CertprofileException) KeyStoreException(java.security.KeyStoreException) XiSecurityException(org.xipki.security.exception.XiSecurityException) CertificateEncodingException(java.security.cert.CertificateEncodingException) InvalidConfException(org.xipki.common.InvalidConfException) SocketException(java.net.SocketException) IOException(java.io.IOException) CertPublisherException(org.xipki.ca.api.publisher.CertPublisherException) OperationException(org.xipki.ca.api.OperationException) CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) ObjectCreationException(org.xipki.common.ObjectCreationException) DataAccessException(org.xipki.datasource.DataAccessException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) CertificateException(java.security.cert.CertificateException) PasswordResolverException(org.xipki.password.PasswordResolverException) CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) ASN1Set(org.bouncycastle.asn1.ASN1Set) CmpControl(org.xipki.ca.server.mgmt.api.CmpControl) PciAuditEvent(org.xipki.audit.PciAuditEvent) AuditEvent(org.xipki.audit.AuditEvent) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) OperationException(org.xipki.ca.api.OperationException)

Example 14 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class RestImpl method service.

public RestResponse service(String path, AuditEvent event, byte[] request, HttpRequestMetadataRetriever httpRetriever) {
    event.setApplicationName(CaAuditConstants.APPNAME);
    event.setName(CaAuditConstants.NAME_PERF);
    event.addEventData(CaAuditConstants.NAME_reqType, RequestType.REST.name());
    String msgId = RandomUtil.nextHexLong();
    event.addEventData(CaAuditConstants.NAME_mid, msgId);
    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;
    try {
        if (responderManager == null) {
            String message = "responderManager in servlet not configured";
            LOG.error(message);
            throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.ERROR, AuditStatus.FAILED);
        }
        String caName = null;
        String command = null;
        X509Ca ca = null;
        if (path.length() > 1) {
            // the first char is always '/'
            String coreUri = path;
            int sepIndex = coreUri.indexOf('/', 1);
            if (sepIndex == -1 || sepIndex == coreUri.length() - 1) {
                String message = "invalid path " + path;
                LOG.error(message);
                throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, null, message, AuditLevel.ERROR, AuditStatus.FAILED);
            }
            // skip also the first char ('/')
            String caAlias = coreUri.substring(1, sepIndex);
            command = coreUri.substring(sepIndex + 1);
            caName = responderManager.getCaNameForAlias(caAlias);
            if (caName == null) {
                caName = caAlias.toLowerCase();
            }
            ca = ((X509CaCmpResponderImpl) responderManager.getX509CaResponder(caName)).getCa();
        }
        if (caName == null || ca == null || ca.getCaInfo().getStatus() != CaStatus.ACTIVE) {
            String message;
            if (caName == null) {
                message = "no CA is specified";
            } else if (ca == null) {
                message = "unknown CA '" + caName + "'";
            } else {
                message = "CA '" + caName + "' is out of service";
            }
            LOG.warn(message);
            throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, null, message, AuditLevel.INFO, AuditStatus.FAILED);
        }
        event.addEventData(CaAuditConstants.NAME_ca, ca.getCaIdent().getName());
        event.addEventType(command);
        RequestorInfo requestor;
        // Retrieve the user:password
        String hdrValue = httpRetriever.getHeader("Authorization");
        if (hdrValue != null && hdrValue.startsWith("Basic ")) {
            String user = null;
            byte[] password = null;
            if (hdrValue.length() > 6) {
                String b64 = hdrValue.substring(6);
                byte[] userPwd = Base64.decodeFast(b64);
                int idx = -1;
                for (int i = 0; i < userPwd.length; i++) {
                    if (userPwd[i] == ':') {
                        idx = i;
                        break;
                    }
                }
                if (idx != -1 && idx < userPwd.length - 1) {
                    user = new String(Arrays.copyOfRange(userPwd, 0, idx));
                    password = Arrays.copyOfRange(userPwd, idx + 1, userPwd.length);
                }
            }
            if (user == null) {
                throw new HttpRespAuditException(HttpResponseStatus.UNAUTHORIZED, "invalid Authorization information", AuditLevel.INFO, AuditStatus.FAILED);
            }
            NameId userIdent = ca.authenticateUser(user, password);
            if (userIdent == null) {
                throw new HttpRespAuditException(HttpResponseStatus.UNAUTHORIZED, "could not authenticate user", AuditLevel.INFO, AuditStatus.FAILED);
            }
            requestor = ca.getByUserRequestor(userIdent);
        } else {
            X509Certificate clientCert = httpRetriever.getTlsClientCert();
            if (clientCert == null) {
                throw new HttpRespAuditException(HttpResponseStatus.UNAUTHORIZED, null, "no client certificate", AuditLevel.INFO, AuditStatus.FAILED);
            }
            requestor = ca.getRequestor(clientCert);
        }
        if (requestor == null) {
            throw new OperationException(ErrorCode.NOT_PERMITTED, "no requestor specified");
        }
        event.addEventData(CaAuditConstants.NAME_requestor, requestor.getIdent().getName());
        String respCt = null;
        byte[] respBytes = null;
        if (RestAPIConstants.CMD_cacert.equalsIgnoreCase(command)) {
            respCt = RestAPIConstants.CT_pkix_cert;
            respBytes = ca.getCaInfo().getCert().getEncodedCert();
        } else if (RestAPIConstants.CMD_enroll_cert.equalsIgnoreCase(command)) {
            String profile = httpRetriever.getParameter(RestAPIConstants.PARAM_profile);
            if (StringUtil.isBlank(profile)) {
                throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "required parameter " + RestAPIConstants.PARAM_profile + " not specified", AuditLevel.INFO, AuditStatus.FAILED);
            }
            profile = profile.toLowerCase();
            try {
                requestor.assertPermitted(PermissionConstants.ENROLL_CERT);
            } catch (InsuffientPermissionException ex) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
            }
            if (!requestor.isCertProfilePermitted(profile)) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, "certProfile " + profile + " is not allowed");
            }
            String ct = httpRetriever.getHeader("Content-Type");
            if (!RestAPIConstants.CT_pkcs10.equalsIgnoreCase(ct)) {
                String message = "unsupported media type " + ct;
                throw new HttpRespAuditException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, message, AuditLevel.INFO, AuditStatus.FAILED);
            }
            String strNotBefore = httpRetriever.getParameter(RestAPIConstants.PARAM_not_before);
            Date notBefore = (strNotBefore == null) ? null : DateUtil.parseUtcTimeyyyyMMddhhmmss(strNotBefore);
            String strNotAfter = httpRetriever.getParameter(RestAPIConstants.PARAM_not_after);
            Date notAfter = (strNotAfter == null) ? null : DateUtil.parseUtcTimeyyyyMMddhhmmss(strNotAfter);
            byte[] encodedCsr = request;
            CertificationRequest csr = CertificationRequest.getInstance(encodedCsr);
            ca.checkCsr(csr);
            CertificationRequestInfo certTemp = csr.getCertificationRequestInfo();
            X500Name subject = certTemp.getSubject();
            SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();
            Extensions extensions = CaUtil.getExtensions(certTemp);
            CertTemplateData certTemplate = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter, extensions, profile);
            X509CertificateInfo certInfo = ca.generateCertificate(certTemplate, requestor, RequestType.REST, null, msgId);
            if (ca.getCaInfo().isSaveRequest()) {
                long dbId = ca.addRequest(encodedCsr);
                ca.addRequestCert(dbId, certInfo.getCert().getCertId());
            }
            X509Cert cert = certInfo.getCert();
            if (cert == null) {
                String message = "could not generate certificate";
                LOG.warn(message);
                throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.INFO, AuditStatus.FAILED);
            }
            respCt = RestAPIConstants.CT_pkix_cert;
            respBytes = cert.getEncodedCert();
        } else if (RestAPIConstants.CMD_revoke_cert.equalsIgnoreCase(command) || RestAPIConstants.CMD_delete_cert.equalsIgnoreCase(command)) {
            int permission;
            if (RestAPIConstants.CMD_revoke_cert.equalsIgnoreCase(command)) {
                permission = PermissionConstants.REVOKE_CERT;
            } else {
                permission = PermissionConstants.REMOVE_CERT;
            }
            try {
                requestor.assertPermitted(permission);
            } catch (InsuffientPermissionException ex) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
            }
            String strCaSha1 = httpRetriever.getParameter(RestAPIConstants.PARAM_ca_sha1);
            if (StringUtil.isBlank(strCaSha1)) {
                throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "required parameter " + RestAPIConstants.PARAM_ca_sha1 + " not specified", AuditLevel.INFO, AuditStatus.FAILED);
            }
            String strSerialNumber = httpRetriever.getParameter(RestAPIConstants.PARAM_serial_number);
            if (StringUtil.isBlank(strSerialNumber)) {
                throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "required parameter " + RestAPIConstants.PARAM_serial_number + " not specified", AuditLevel.INFO, AuditStatus.FAILED);
            }
            if (!strCaSha1.equalsIgnoreCase(ca.getHexSha1OfCert())) {
                throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "unknown " + RestAPIConstants.PARAM_ca_sha1, AuditLevel.INFO, AuditStatus.FAILED);
            }
            BigInteger serialNumber = toBigInt(strSerialNumber);
            if (RestAPIConstants.CMD_revoke_cert.equalsIgnoreCase(command)) {
                String strReason = httpRetriever.getParameter(RestAPIConstants.PARAM_reason);
                CrlReason reason = (strReason == null) ? CrlReason.UNSPECIFIED : CrlReason.forNameOrText(strReason);
                if (reason == CrlReason.REMOVE_FROM_CRL) {
                    ca.unrevokeCertificate(serialNumber, msgId);
                } else {
                    Date invalidityTime = null;
                    String strInvalidityTime = httpRetriever.getParameter(RestAPIConstants.PARAM_invalidity_time);
                    if (StringUtil.isNotBlank(strInvalidityTime)) {
                        invalidityTime = DateUtil.parseUtcTimeyyyyMMddhhmmss(strInvalidityTime);
                    }
                    ca.revokeCertificate(serialNumber, reason, invalidityTime, msgId);
                }
            } else if (RestAPIConstants.CMD_delete_cert.equalsIgnoreCase(command)) {
                ca.removeCertificate(serialNumber, msgId);
            }
        } else if (RestAPIConstants.CMD_crl.equalsIgnoreCase(command)) {
            try {
                requestor.assertPermitted(PermissionConstants.GET_CRL);
            } catch (InsuffientPermissionException ex) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
            }
            String strCrlNumber = httpRetriever.getParameter(RestAPIConstants.PARAM_crl_number);
            BigInteger crlNumber = null;
            if (StringUtil.isNotBlank(strCrlNumber)) {
                try {
                    crlNumber = toBigInt(strCrlNumber);
                } catch (NumberFormatException ex) {
                    String message = "invalid crlNumber '" + strCrlNumber + "'";
                    LOG.warn(message);
                    throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, message, AuditLevel.INFO, AuditStatus.FAILED);
                }
            }
            X509CRL crl = ca.getCrl(crlNumber);
            if (crl == null) {
                String message = "could not get CRL";
                LOG.warn(message);
                throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.INFO, AuditStatus.FAILED);
            }
            respCt = RestAPIConstants.CT_pkix_crl;
            respBytes = crl.getEncoded();
        } else if (RestAPIConstants.CMD_new_crl.equalsIgnoreCase(command)) {
            try {
                requestor.assertPermitted(PermissionConstants.GEN_CRL);
            } catch (InsuffientPermissionException ex) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
            }
            X509CRL crl = ca.generateCrlOnDemand(msgId);
            if (crl == null) {
                String message = "could not generate CRL";
                LOG.warn(message);
                throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.INFO, AuditStatus.FAILED);
            }
            respCt = RestAPIConstants.CT_pkix_crl;
            respBytes = crl.getEncoded();
        } else {
            String message = "invalid command '" + command + "'";
            LOG.error(message);
            throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, message, AuditLevel.INFO, AuditStatus.FAILED);
        }
        Map<String, String> headers = new HashMap<>();
        headers.put(RestAPIConstants.HEADER_PKISTATUS, RestAPIConstants.PKISTATUS_accepted);
        return new RestResponse(HttpResponseStatus.OK, respCt, headers, respBytes);
    } catch (OperationException ex) {
        ErrorCode code = ex.getErrorCode();
        if (LOG.isWarnEnabled()) {
            String msg = StringUtil.concat("generate certificate, OperationException: code=", code.name(), ", message=", ex.getErrorMessage());
            LOG.warn(msg);
            LOG.debug(msg, ex);
        }
        int sc;
        String failureInfo;
        switch(code) {
            case ALREADY_ISSUED:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badRequest;
                break;
            case BAD_CERT_TEMPLATE:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badCertTemplate;
                break;
            case BAD_REQUEST:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badRequest;
                break;
            case CERT_REVOKED:
                sc = HttpResponseStatus.CONFLICT;
                failureInfo = RestAPIConstants.FAILINFO_certRevoked;
                break;
            case CRL_FAILURE:
                sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                failureInfo = RestAPIConstants.FAILINFO_systemFailure;
                break;
            case DATABASE_FAILURE:
                sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                failureInfo = RestAPIConstants.FAILINFO_systemFailure;
                break;
            case NOT_PERMITTED:
                sc = HttpResponseStatus.UNAUTHORIZED;
                failureInfo = RestAPIConstants.FAILINFO_notAuthorized;
                break;
            case INVALID_EXTENSION:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badRequest;
                break;
            case SYSTEM_FAILURE:
                sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                failureInfo = RestAPIConstants.FAILINFO_systemFailure;
                break;
            case SYSTEM_UNAVAILABLE:
                sc = HttpResponseStatus.SERVICE_UNAVAILABLE;
                failureInfo = RestAPIConstants.FAILINFO_systemUnavail;
                break;
            case UNKNOWN_CERT:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badCertId;
                break;
            case UNKNOWN_CERT_PROFILE:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badCertTemplate;
                break;
            default:
                sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                failureInfo = RestAPIConstants.FAILINFO_systemFailure;
                break;
        }
        // end switch (code)
        event.setStatus(AuditStatus.FAILED);
        event.addEventData(CaAuditConstants.NAME_message, code.name());
        switch(code) {
            case DATABASE_FAILURE:
            case SYSTEM_FAILURE:
                auditMessage = code.name();
                break;
            default:
                auditMessage = code.name() + ": " + ex.getErrorMessage();
                break;
        }
        // end switch code
        Map<String, String> headers = new HashMap<>();
        headers.put(RestAPIConstants.HEADER_PKISTATUS, RestAPIConstants.PKISTATUS_rejection);
        if (StringUtil.isNotBlank(failureInfo)) {
            headers.put(RestAPIConstants.HEADER_failInfo, failureInfo);
        }
        return new RestResponse(sc, null, headers, null);
    } catch (HttpRespAuditException ex) {
        auditStatus = ex.getAuditStatus();
        auditLevel = ex.getAuditLevel();
        auditMessage = ex.getAuditMessage();
        return new RestResponse(ex.getHttpStatus(), null, null, null);
    } catch (Throwable th) {
        if (th instanceof EOFException) {
            LogUtil.warn(LOG, th, "connection reset by peer");
        } else {
            LOG.error("Throwable thrown, this should not happen!", th);
        }
        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = "internal error";
        return new RestResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, null, null);
    } finally {
        event.setStatus(auditStatus);
        event.setLevel(auditLevel);
        if (auditMessage != null) {
            event.addEventData(CaAuditConstants.NAME_message, auditMessage);
        }
    }
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) X509CRL(java.security.cert.X509CRL) NameId(org.xipki.ca.api.NameId) HashMap(java.util.HashMap) X509Ca(org.xipki.ca.server.impl.X509Ca) InsuffientPermissionException(org.xipki.ca.api.InsuffientPermissionException) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertTemplateData(org.xipki.ca.server.impl.CertTemplateData) X509Cert(org.xipki.security.X509Cert) EOFException(java.io.EOFException) CrlReason(org.xipki.security.CrlReason) OperationException(org.xipki.ca.api.OperationException) RestResponse(org.xipki.ca.server.api.RestResponse) AuditLevel(org.xipki.audit.AuditLevel) X509CertificateInfo(org.xipki.ca.api.publisher.x509.X509CertificateInfo) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) AuditStatus(org.xipki.audit.AuditStatus) BigInteger(java.math.BigInteger) ErrorCode(org.xipki.ca.api.OperationException.ErrorCode) HashMap(java.util.HashMap) Map(java.util.Map) RequestorInfo(org.xipki.ca.server.mgmt.api.RequestorInfo) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 15 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class CertPollCmd method execute0.

@Override
protected Object execute0() throws Exception {
    CertificationRequest csr = CertificationRequest.getInstance(IoUtil.read(csrFile));
    ScepClient client = getScepClient();
    X509Certificate caCert = client.getAuthorityCertStore().getCaCert();
    X500Name caSubject = X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded());
    EnrolmentResponse resp = client.scepCertPoll(getIdentityKey(), getIdentityCert(), csr, caSubject);
    if (resp.isFailure()) {
        throw new CmdFailure("server returned 'failure'");
    }
    if (resp.isPending()) {
        throw new CmdFailure("server returned 'pending'");
    }
    List<X509Certificate> certs = resp.getCertificates();
    if (certs == null || certs.isEmpty()) {
        throw new CmdFailure("received no certficate from server");
    }
    saveVerbose("saved certificate to file", new File(outputFile), certs.get(0).getEncoded());
    return null;
}
Also used : CmdFailure(org.xipki.console.karaf.CmdFailure) ScepClient(org.xipki.scep.client.ScepClient) EnrolmentResponse(org.xipki.scep.client.EnrolmentResponse) X500Name(org.bouncycastle.asn1.x500.X500Name) File(java.io.File) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) X509Certificate(java.security.cert.X509Certificate)

Aggregations

CertificationRequest (org.bouncycastle.asn1.pkcs.CertificationRequest)24 X500Name (org.bouncycastle.asn1.x500.X500Name)12 X509Certificate (java.security.cert.X509Certificate)9 Date (java.util.Date)9 BigInteger (java.math.BigInteger)8 CertificationRequestInfo (org.bouncycastle.asn1.pkcs.CertificationRequestInfo)8 X509Cert (org.xipki.security.X509Cert)8 Extensions (org.bouncycastle.asn1.x509.Extensions)7 File (java.io.File)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 PrivateKey (java.security.PrivateKey)5 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)5 OperationException (org.xipki.ca.api.OperationException)5 IOException (java.io.IOException)4 CertificateException (java.security.cert.CertificateException)4 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)4 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)4 IssuerAndSerialNumber (org.bouncycastle.asn1.cms.IssuerAndSerialNumber)4 EnrolmentResponse (org.xipki.scep.client.EnrolmentResponse)4 ScepClient (org.xipki.scep.client.ScepClient)4