Search in sources :

Example 6 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class CmpCaClientExample method main.

public static void main(String[] args) {
    try {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        char[] password = REQUESTOR_KEYSTORE_PASSWORD.toCharArray();
        FileInputStream ksStream = new FileInputStream(expandPath(REQUESTOR_KEYSTORE_FILE));
        ks.load(ksStream, password);
        ksStream.close();
        Enumeration<String> aliases = ks.aliases();
        String alias = null;
        while (aliases.hasMoreElements()) {
            String tmp = aliases.nextElement();
            if (ks.isKeyEntry(tmp)) {
                alias = tmp;
                break;
            }
        }
        PrivateKey requestorKey = (PrivateKey) ks.getKey(alias, password);
        X509Certificate requestorCert = (X509Certificate) ks.getCertificate(alias);
        X509Certificate caCert = SdkUtil.parseCert(new File(expandPath(CA_CERT_FILE)));
        X509Certificate responderCert = SdkUtil.parseCert(new File(expandPath(RESPONDER_CERT_FILE)));
        CmpCaClient client = new CmpCaClient(CA_URL, caCert, requestorKey, requestorCert, responderCert, HASH_ALGO);
        // Since xipki-2.2.1 the specification of CA certificate is not required, it can
        // be retrieved via the CMP protocol
        // 
        // CmpCaClient client = new CmpCaClient(CA_URL, requestorKey, requestorCert,
        // responderCert, HASH_ALGO);
        client.init();
        // retrieve CA certificate
        printCert("===== CA Certificate =====", client.getCaCert());
        // Enroll certificate via CSR - RSA
        MyKeypair kp = generateRsaKeypair();
        CertificationRequest csr = genCsr(kp, getSubject());
        X509Certificate cert = client.requestCertViaCsr(CERT_PROFILE, csr);
        printCert("===== RSA via CSR (CMP) =====", cert);
        // Enroll certificate via CSR - EC
        kp = generateEcKeypair();
        csr = genCsr(kp, getSubject());
        cert = client.requestCertViaCsr(CERT_PROFILE, csr);
        printCert("===== EC via CSR (CMP) =====", cert);
        // Enroll certificate via CSR - DSA
        kp = generateDsaKeypair();
        csr = genCsr(kp, getSubject());
        cert = client.requestCertViaCsr(CERT_PROFILE, csr);
        printCert("===== DSA via CSR (CMP) =====", cert);
        // Enroll certificate via CRMF - RSA
        kp = generateRsaKeypair();
        cert = client.requestCertViaCrmf(CERT_PROFILE, kp.getPrivate(), kp.getPublic(), getSubject());
        printCert("===== RSA via CRMF (CMP) =====", cert);
        // Enroll certificate via CRMF - EC
        kp = generateEcKeypair();
        cert = client.requestCertViaCrmf(CERT_PROFILE, kp.getPrivate(), kp.getPublic(), getSubject());
        printCert("===== EC via CRMF (CMP) =====", cert);
        // Enroll certificate via CRMF - DSA
        kp = generateDsaKeypair();
        cert = client.requestCertViaCrmf(CERT_PROFILE, kp.getPrivate(), kp.getPublic(), getSubject());
        printCert("===== DSA via CRMF (CMP) =====", cert);
        BigInteger serialNumber = cert.getSerialNumber();
        // Suspend certificate
        boolean flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.certificateHold));
        if (flag) {
            System.out.println("(CMP) suspended certificate");
        } else {
            System.err.println("(CMP) suspending certificate failed");
        }
        // Unsuspend certificate
        flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.removeFromCRL));
        if (flag) {
            System.out.println("(CMP) unsuspended certificate");
        } else {
            System.err.println("(CMP) unsuspending certificate failed");
        }
        // Revoke certificate
        flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.keyCompromise));
        if (flag) {
            System.out.println("(CMP) revoked certificate");
        } else {
            System.err.println("(CMP) revoking certificate failed");
        }
        client.shutdown();
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(-1);
    }
}
Also used : PrivateKey(java.security.PrivateKey) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) CmpCaClient(org.xipki.litecaclient.CmpCaClient) File(java.io.File) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 7 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class CaClientExample method genCsr.

protected static CertificationRequest genCsr(MyKeypair keypair, String subject, String challengePassword) throws GeneralSecurityException, OperatorCreationException {
    X500Name subjectDn = new X500Name(subject);
    PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(subjectDn, keypair.publicKeyInfo);
    if (challengePassword != null && !challengePassword.isEmpty()) {
        csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword));
    }
    ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
    return csrBuilder.build(signer).toASN1Structure();
}
Also used : DERPrintableString(org.bouncycastle.asn1.DERPrintableString) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name)

Example 8 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class X509SelfSignedCertBuilder method generateSelfSigned.

public static GenerateSelfSignedResult generateSelfSigned(SecurityFactory securityFactory, String signerType, String signerConf, IdentifiedX509Certprofile certprofile, CertificationRequest csr, BigInteger serialNumber, List<String> caCertUris, List<String> ocspUris, List<String> crlUris, List<String> deltaCrlUris, ConfPairs extraControl) throws OperationException, InvalidConfException {
    ParamUtil.requireNonNull("securityFactory", securityFactory);
    ParamUtil.requireNonBlank("signerType", signerType);
    ParamUtil.requireNonNull("certprofile", certprofile);
    ParamUtil.requireNonNull("csr", csr);
    ParamUtil.requireNonNull("serialNumber", serialNumber);
    if (serialNumber.compareTo(BigInteger.ZERO) != 1) {
        throw new IllegalArgumentException("serialNumber must not be non-positive: " + serialNumber);
    }
    X509CertLevel level = certprofile.getCertLevel();
    if (X509CertLevel.RootCA != level) {
        throw new IllegalArgumentException("certprofile is not of level " + X509CertLevel.RootCA);
    }
    if (!securityFactory.verifyPopo(csr, null)) {
        throw new InvalidConfException("could not validate POP for the CSR");
    }
    if ("pkcs12".equalsIgnoreCase(signerType) || "jks".equalsIgnoreCase(signerType)) {
        ConfPairs keyValues = new ConfPairs(signerConf);
        String keystoreConf = keyValues.value("keystore");
        if (keystoreConf == null) {
            throw new InvalidConfException("required parameter 'keystore' for types PKCS12 and JKS, is not specified");
        }
    }
    ConcurrentContentSigner signer;
    try {
        List<String[]> signerConfs = CaEntry.splitCaSignerConfs(signerConf);
        List<String> restrictedSigAlgos = certprofile.getSignatureAlgorithms();
        String thisSignerConf = null;
        if (CollectionUtil.isEmpty(restrictedSigAlgos)) {
            thisSignerConf = signerConfs.get(0)[1];
        } else {
            for (String algo : restrictedSigAlgos) {
                for (String[] m : signerConfs) {
                    if (m[0].equals(algo)) {
                        thisSignerConf = m[1];
                        break;
                    }
                }
                if (thisSignerConf != null) {
                    break;
                }
            }
        }
        if (thisSignerConf == null) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile");
        }
        signer = securityFactory.createSigner(signerType, new SignerConf(thisSignerConf), (X509Certificate[]) null);
    } catch (XiSecurityException | ObjectCreationException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
    }
    SubjectPublicKeyInfo publicKeyInfo;
    if (signer.getCertificate() != null) {
        // this cert is the dummy one which can be considered only as public key container
        Certificate bcCert;
        try {
            bcCert = Certificate.getInstance(signer.getCertificate().getEncoded());
        } catch (Exception ex) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not reparse certificate: " + ex.getMessage());
        }
        publicKeyInfo = bcCert.getSubjectPublicKeyInfo();
    } else {
        PublicKey signerPublicKey = signer.getPublicKey();
        try {
            publicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signerPublicKey);
        } catch (InvalidKeyException ex) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "cannot generate SubjectPublicKeyInfo from publicKey: " + ex.getMessage());
        }
    }
    X509Certificate newCert = generateCertificate(signer, certprofile, csr, serialNumber, publicKeyInfo, caCertUris, ocspUris, crlUris, deltaCrlUris, extraControl);
    return new GenerateSelfSignedResult(signerConf, newCert);
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) PublicKey(java.security.PublicKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) InvalidConfException(org.xipki.common.InvalidConfException) ConfPairs(org.xipki.common.ConfPairs) SignerConf(org.xipki.security.SignerConf) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertprofileException(org.xipki.ca.api.profile.CertprofileException) ObjectCreationException(org.xipki.common.ObjectCreationException) InvalidKeyException(java.security.InvalidKeyException) XiSecurityException(org.xipki.security.exception.XiSecurityException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) InvalidConfException(org.xipki.common.InvalidConfException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) OperationException(org.xipki.ca.api.OperationException) X509Certificate(java.security.cert.X509Certificate) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) XiSecurityException(org.xipki.security.exception.XiSecurityException) ObjectCreationException(org.xipki.common.ObjectCreationException) X509CertLevel(org.xipki.ca.api.profile.x509.X509CertLevel) OperationException(org.xipki.ca.api.OperationException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 9 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class X509SelfSignedCertBuilder method generateCertificate.

// method generateSelfSigned
private static X509Certificate generateCertificate(ConcurrentContentSigner signer, IdentifiedX509Certprofile certprofile, CertificationRequest csr, BigInteger serialNumber, SubjectPublicKeyInfo publicKeyInfo, List<String> caCertUris, List<String> ocspUris, List<String> crlUris, List<String> deltaCrlUris, ConfPairs extraControl) throws OperationException {
    SubjectPublicKeyInfo tmpPublicKeyInfo;
    try {
        tmpPublicKeyInfo = X509Util.toRfc3279Style(publicKeyInfo);
    } catch (InvalidKeySpecException ex) {
        LOG.warn("SecurityUtil.toRfc3279Style", ex);
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }
    try {
        certprofile.checkPublicKey(tmpPublicKeyInfo);
    } catch (BadCertTemplateException ex) {
        LOG.warn("certprofile.checkPublicKey", ex);
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }
    X500Name requestedSubject = csr.getCertificationRequestInfo().getSubject();
    SubjectInfo subjectInfo;
    // subject
    try {
        subjectInfo = certprofile.getSubject(requestedSubject);
    } catch (CertprofileException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofile.getIdent());
    } catch (BadCertTemplateException ex) {
        LOG.warn("certprofile.getSubject", ex);
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }
    Date notBefore = certprofile.getNotBefore(null);
    if (notBefore == null) {
        notBefore = new Date();
    }
    CertValidity validity = certprofile.getValidity();
    if (validity == null) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "no validity specified in the profile " + certprofile.getIdent());
    }
    Date notAfter = validity.add(notBefore);
    X500Name grantedSubject = subjectInfo.getGrantedSubject();
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(grantedSubject, serialNumber, notBefore, notAfter, grantedSubject, tmpPublicKeyInfo);
    PublicCaInfo publicCaInfo = new PublicCaInfo(grantedSubject, serialNumber, null, null, caCertUris, ocspUris, crlUris, deltaCrlUris, extraControl);
    Extensions extensions = null;
    ASN1Set attrs = csr.getCertificationRequestInfo().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]);
        }
    }
    try {
        addExtensions(certBuilder, certprofile, requestedSubject, grantedSubject, extensions, tmpPublicKeyInfo, publicCaInfo, notBefore, notAfter);
        ConcurrentBagEntrySigner signer0 = signer.borrowSigner();
        X509CertificateHolder certHolder;
        try {
            certHolder = certBuilder.build(signer0.value());
        } finally {
            signer.requiteSigner(signer0);
        }
        Certificate bcCert = certHolder.toASN1Structure();
        return X509Util.parseCert(bcCert.getEncoded());
    } catch (BadCertTemplateException ex) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    } catch (NoIdleSignerException | CertificateException | IOException | CertprofileException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
    }
}
Also used : CertValidity(org.xipki.ca.api.profile.CertValidity) Attribute(org.bouncycastle.asn1.pkcs.Attribute) SubjectInfo(org.xipki.ca.api.profile.x509.SubjectInfo) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) PublicCaInfo(org.xipki.ca.api.PublicCaInfo) ConcurrentBagEntrySigner(org.xipki.security.ConcurrentBagEntrySigner) Date(java.util.Date) ASN1Set(org.bouncycastle.asn1.ASN1Set) CertprofileException(org.xipki.ca.api.profile.CertprofileException) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) OperationException(org.xipki.ca.api.OperationException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 10 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest 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)

Aggregations

CertificationRequest (org.bouncycastle.asn1.pkcs.CertificationRequest)17 X509Certificate (java.security.cert.X509Certificate)14 X500Name (org.bouncycastle.asn1.x500.X500Name)12 Date (java.util.Date)10 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)7 CertificateException (java.security.cert.CertificateException)6 CertificationRequestInfo (org.bouncycastle.asn1.pkcs.CertificationRequestInfo)6 Extensions (org.bouncycastle.asn1.x509.Extensions)6 OperationException (org.xipki.ca.api.OperationException)6 IOException (java.io.IOException)5 BigInteger (java.math.BigInteger)5 File (java.io.File)4 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)4 PKCS10CertificationRequest (org.bouncycastle.pkcs.PKCS10CertificationRequest)4 EnrolmentResponse (org.xipki.scep.client.EnrolmentResponse)4 ScepClient (org.xipki.scep.client.ScepClient)4 InvalidKeyException (java.security.InvalidKeyException)3 PrivateKey (java.security.PrivateKey)3 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)3 Certificate (org.bouncycastle.asn1.x509.Certificate)3