Search in sources :

Example 1 with CertificationRequestInfo

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequestInfo in project nhin-d by DirectProject.

the class CertGenerator method createCertFromCSR.

public static X509Certificate createCertFromCSR(PKCS10CertificationRequest certReq, CertCreateFields signerCert) throws Exception {
    certReq.verify();
    final CertificationRequestInfo reqInfo = certReq.getCertificationRequestInfo();
    final X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
    final Calendar start = Calendar.getInstance();
    final Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 3);
    v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
    // issuer is the parent cert
    v1CertGen.setIssuerDN(signerCert.getSignerCert().getSubjectX500Principal());
    v1CertGen.setNotBefore(start.getTime());
    v1CertGen.setNotAfter(end.getTime());
    v1CertGen.setSubjectDN(new X509Principal(reqInfo.getSubject().toString()));
    v1CertGen.setPublicKey(certReq.getPublicKey());
    v1CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    final ASN1Set attributesAsn1Set = reqInfo.getAttributes();
    X509Extensions certificateRequestExtensions = null;
    for (int i = 0; i < attributesAsn1Set.size(); ++i) {
        // There should be only only one attribute in the set. (that is, only
        // the `Extension Request`, but loop through to find it properly)
        final DEREncodable derEncodable = attributesAsn1Set.getObjectAt(i);
        if (derEncodable instanceof DERSequence) {
            final Attribute attribute = new Attribute((DERSequence) attributesAsn1Set.getObjectAt(i));
            if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                // The `Extension Request` attribute is present.
                final ASN1Set attributeValues = attribute.getAttrValues();
                // Assume that it is the first value of the set.
                if (attributeValues.size() >= 1) {
                    certificateRequestExtensions = new X509Extensions((ASN1Sequence) attributeValues.getObjectAt(0));
                // No need to search any more.
                //break;
                }
            }
        }
    }
    @SuppressWarnings("unchecked") Enumeration<DERObjectIdentifier> oids = certificateRequestExtensions.oids();
    while (oids.hasMoreElements()) {
        DERObjectIdentifier oid = oids.nextElement();
        X509Extension ex = certificateRequestExtensions.getExtension(oid);
        v1CertGen.addExtension(oid, ex.isCritical(), X509Extension.convertValueToObject(ex));
    }
    return v1CertGen.generate((PrivateKey) signerCert.getSignerKey(), CryptoExtensions.getJCEProviderName());
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) Attribute(org.bouncycastle.asn1.cms.Attribute) X509Extension(org.bouncycastle.asn1.x509.X509Extension) Calendar(java.util.Calendar) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) X509Principal(org.bouncycastle.jce.X509Principal) DEREncodable(org.bouncycastle.asn1.DEREncodable)

Example 2 with CertificationRequestInfo

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

the class X509CaCmpResponderImpl method processP10cr.

// method processCertReqMessages
/**
 * 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
 */
private PKIBody processP10cr(PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertificationRequest p10cr, CmpControl cmpControl, String msgId, 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.value(CmpUtf8Pairs.KEY_CERTPROFILE);
            String str = keyvalues.value(CmpUtf8Pairs.KEY_NOTBEFORE);
            if (str != null) {
                notBefore = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
            }
            str = keyvalues.value(CmpUtf8Pairs.KEY_NOTAFTER);
            if (str != null) {
                notAfter = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
            }
        }
        if (certprofileName == null) {
            certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badCertTemplate, "badCertTemplate", null);
        } else {
            certprofileName = certprofileName.toLowerCase();
            if (!requestor.isCertProfilePermitted(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, 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);
}
Also used : PKIBody(org.bouncycastle.asn1.cmp.PKIBody) CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) CmpUtf8Pairs(org.xipki.cmp.CmpUtf8Pairs) CertResponse(org.bouncycastle.asn1.cmp.CertResponse) X509Ca(org.xipki.ca.server.impl.X509Ca) CertRepMessage(org.bouncycastle.asn1.cmp.CertRepMessage) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) CertTemplateData(org.xipki.ca.server.impl.CertTemplateData) CMPCertificate(org.bouncycastle.asn1.cmp.CMPCertificate)

Example 3 with CertificationRequestInfo

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

the class CheckCertCmd method execute0.

@Override
protected Object execute0() throws Exception {
    Set<String> issuerNames = qaSystemManager.getIssuerNames();
    if (isEmpty(issuerNames)) {
        throw new IllegalCmdParamException("no issuer is configured");
    }
    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;
}
Also used : X509CertprofileQa(org.xipki.ca.qa.X509CertprofileQa) CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) Attribute(org.bouncycastle.asn1.pkcs.Attribute) X509IssuerInfo(org.xipki.ca.qa.X509IssuerInfo) Extensions(org.bouncycastle.asn1.x509.Extensions) ValidationResult(org.xipki.common.qa.ValidationResult) ValidationIssue(org.xipki.common.qa.ValidationIssue) ASN1Set(org.bouncycastle.asn1.ASN1Set) CmdFailure(org.xipki.console.karaf.CmdFailure) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 4 with CertificationRequestInfo

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequestInfo in project jruby-openssl by jruby.

the class PKCS10Request method resetSignedRequest.

private void resetSignedRequest() {
    if (signedRequest == null)
        return;
    CertificationRequest req = signedRequest.toASN1Structure();
    CertificationRequestInfo reqInfo = new CertificationRequestInfo(subject, publicKeyInfo, req.getCertificationRequestInfo().getAttributes());
    ASN1Sequence seq = (ASN1Sequence) req.toASN1Primitive();
    req = new CertificationRequest(reqInfo, (AlgorithmIdentifier) seq.getObjectAt(1), (DERBitString) seq.getObjectAt(2));
    // valid = true;
    signedRequest = new PKCS10CertificationRequest(req);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERBitString(org.bouncycastle.asn1.DERBitString) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 5 with CertificationRequestInfo

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

the class CmpResponder method processP10cr.

// method processCertReqMessages
/**
 * 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
 */
private PKIBody processP10cr(String dfltCertprofileName, PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertificationRequest p10cr, CmpControl cmpControl, String msgId, AuditEvent event) {
    // verify the POP first
    CertResponse certResp = null;
    ASN1Integer certReqId = new ASN1Integer(-1);
    boolean certGenerated = false;
    X509Ca ca = getCa();
    if (!ca.verifyCsr(p10cr)) {
        LOG.warn("could not validate POP for the pkcs#10 requst");
        certResp = buildErrCertResp(certReqId, badPOP, "invalid POP");
    } else {
        CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
        Extensions extensions;
        try {
            extensions = CaUtil.getExtensions(certTemp);
        } catch (IllegalArgumentException ex) {
            extensions = null;
            LOG.warn("could not parse extensions of the pkcs#10 requst");
            certResp = buildErrCertResp(certReqId, badCertTemplate, "invalid extensions");
        }
        if (certResp == null) {
            X500Name subject = certTemp.getSubject();
            SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();
            InfoTypeAndValue[] generalInfo = reqHeader.getGeneralInfo();
            CmpUtf8Pairs keyvalues = CmpUtil.extractUtf8Pairs(generalInfo);
            // CertProfile name
            String certprofileName = null;
            String[] list = CmpUtil.extractCertProfile(generalInfo);
            if (list != null && list.length > 0) {
                certprofileName = list[0];
            } else {
                if (keyvalues != null) {
                    certprofileName = keyvalues.value(KEY_CERTPROFILE);
                }
            }
            // NotBefore and NotAfter
            Date notBefore = null;
            Date notAfter = null;
            if (keyvalues != null) {
                String str = keyvalues.value(CmpUtf8Pairs.KEY_NOTBEFORE);
                if (str != null) {
                    notBefore = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
                }
                str = keyvalues.value(CmpUtf8Pairs.KEY_NOTAFTER);
                if (str != null) {
                    notAfter = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
                }
            }
            if (certprofileName == null) {
                certprofileName = dfltCertprofileName;
            }
            if (certprofileName == null) {
                LOG.warn("no certprofile is specified");
                certResp = buildErrCertResp(certReqId, badCertTemplate, "badCertTemplate");
            } else {
                certprofileName = certprofileName.toLowerCase();
                if (!requestor.isCertprofilePermitted(certprofileName)) {
                    String msg = "certprofile " + certprofileName + " is not allowed";
                    certResp = buildErrCertResp(certReqId, notAuthorized, msg);
                } else {
                    CertTemplateData certTemplateData = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter, extensions, certprofileName, certReqId, false);
                    certResp = generateCertificates(Collections.singletonList(certTemplateData), requestor, tid, false, request, cmpControl, msgId, event).get(0);
                    certGenerated = true;
                }
            }
        }
    }
    CMPCertificate[] caPubs = null;
    if (certGenerated && (cmpControl.isSendCaCert() || cmpControl.isSendCertChain())) {
        List<CMPCertificate> certchain = new ArrayList<>(2);
        certchain.add(getCa().getCaInfo().getCertInCmpFormat());
        if (cmpControl.isSendCertChain()) {
            certchain.addAll(getCa().getCaInfo().getCertchainInCmpFormat());
        }
        caPubs = certchain.toArray(new CMPCertificate[0]);
    }
    if (event.getStatus() == null || event.getStatus() != AuditStatus.FAILED) {
        int status = certResp.getStatus().getStatus().intValue();
        if (status != GRANTED && status != GRANTED_WITH_MODS && status != WAITING) {
            event.setStatus(AuditStatus.FAILED);
            PKIFreeText statusStr = certResp.getStatus().getStatusString();
            if (statusStr != null) {
                event.addEventData(CaAuditConstants.NAME_message, statusStr.getStringAt(0).getString());
            }
        }
    }
    return new PKIBody(PKIBody.TYPE_CERT_REP, new CertRepMessage(caPubs, new CertResponse[] { certResp }));
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) CmpUtf8Pairs(org.xipki.security.cmp.CmpUtf8Pairs) X509Ca(org.xipki.ca.server.X509Ca) X500Name(org.bouncycastle.asn1.x500.X500Name) CertTemplateData(org.xipki.ca.server.CertTemplateData)

Aggregations

CertificationRequestInfo (org.bouncycastle.asn1.pkcs.CertificationRequestInfo)11 CertificationRequest (org.bouncycastle.asn1.pkcs.CertificationRequest)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 Extensions (org.bouncycastle.asn1.x509.Extensions)8 Date (java.util.Date)5 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)5 OperationException (org.xipki.ca.api.OperationException)5 BigInteger (java.math.BigInteger)4 ASN1Set (org.bouncycastle.asn1.ASN1Set)4 IOException (java.io.IOException)3 Attribute (org.bouncycastle.asn1.pkcs.Attribute)3 NameId (org.xipki.ca.api.NameId)3 X509CertificateInfo (org.xipki.ca.api.publisher.x509.X509CertificateInfo)3 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)2 CertificationRequestInfo (com.github.zhenwei.core.asn1.pkcs.CertificationRequestInfo)2 EOFException (java.io.EOFException)2 OutputStream (java.io.OutputStream)2 CertificateException (java.security.cert.CertificateException)2 X509Certificate (java.security.cert.X509Certificate)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2