Search in sources :

Example 1 with CertificationRequest

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

the class CsrEnrollCertCmd method execute0.

@Override
protected Object execute0() throws Exception {
    if (caName != null) {
        caName = caName.toLowerCase();
    }
    CertificationRequest csr = CertificationRequest.getInstance(IoUtil.read(csrFile));
    Date notBefore = StringUtil.isNotBlank(notBeforeS) ? DateUtil.parseUtcTimeyyyyMMddhhmmss(notBeforeS) : null;
    Date notAfter = StringUtil.isNotBlank(notAfterS) ? DateUtil.parseUtcTimeyyyyMMddhhmmss(notAfterS) : null;
    EnrollCertResult result;
    RequestResponseDebug debug = getRequestResponseDebug();
    try {
        result = caClient.requestCert(caName, csr, profile, notBefore, notAfter, debug);
    } finally {
        saveRequestResponse(debug);
    }
    X509Certificate cert = null;
    if (result != null) {
        String id = result.getAllIds().iterator().next();
        CertOrError certOrError = result.getCertOrError(id);
        cert = (X509Certificate) certOrError.getCertificate();
    }
    if (cert == null) {
        throw new CmdFailure("no certificate received from the server");
    }
    File certFile = new File(outputFile);
    saveVerbose("certificate saved to file", certFile, cert.getEncoded());
    return null;
}
Also used : RequestResponseDebug(org.xipki.common.RequestResponseDebug) CmdFailure(org.xipki.console.karaf.CmdFailure) EnrollCertResult(org.xipki.ca.client.api.EnrollCertResult) CertOrError(org.xipki.ca.client.api.CertOrError) File(java.io.File) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 2 with CertificationRequest

use of com.github.zhenwei.core.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 3 with CertificationRequest

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

the class CaManagerImpl method generateRootCa.

// method getIdentifiedPublishersForCa
@Override
public X509Certificate generateRootCa(X509CaEntry caEntry, String profileName, byte[] encodedCsr, BigInteger serialNumber) throws CaMgmtException {
    ParamUtil.requireNonNull("caEntry", caEntry);
    profileName = ParamUtil.requireNonBlank("profileName", profileName).toLowerCase();
    ParamUtil.requireNonNull("encodedCsr", encodedCsr);
    int numCrls = caEntry.getNumCrls();
    List<String> crlUris = caEntry.getCrlUris();
    List<String> deltaCrlUris = caEntry.getDeltaCrlUris();
    List<String> ocspUris = caEntry.getOcspUris();
    List<String> caCertUris = caEntry.getCaCertUris();
    String signerType = caEntry.getSignerType();
    asssertMasterMode();
    if (numCrls < 0) {
        System.err.println("invalid numCrls: " + numCrls);
        return null;
    }
    int expirationPeriod = caEntry.getExpirationPeriod();
    if (expirationPeriod < 0) {
        System.err.println("invalid expirationPeriod: " + expirationPeriod);
        return null;
    }
    CertificationRequest csr;
    try {
        csr = CertificationRequest.getInstance(encodedCsr);
    } catch (Exception ex) {
        System.err.println("invalid encodedCsr");
        return null;
    }
    IdentifiedX509Certprofile certprofile = getIdentifiedCertprofile(profileName);
    if (certprofile == null) {
        throw new CaMgmtException(concat("unknown certprofile ", profileName));
    }
    BigInteger serialOfThisCert = (serialNumber != null) ? serialNumber : RandomSerialNumberGenerator.getInstance().nextSerialNumber(caEntry.getSerialNoBitLen());
    GenerateSelfSignedResult result;
    try {
        result = X509SelfSignedCertBuilder.generateSelfSigned(securityFactory, signerType, caEntry.getSignerConf(), certprofile, csr, serialOfThisCert, caCertUris, ocspUris, crlUris, deltaCrlUris, caEntry.getExtraControl());
    } catch (OperationException | InvalidConfException ex) {
        throw new CaMgmtException(concat(ex.getClass().getName(), ": ", ex.getMessage()), ex);
    }
    String signerConf = result.getSignerConf();
    X509Certificate caCert = result.getCert();
    if ("PKCS12".equalsIgnoreCase(signerType) || "JKS".equalsIgnoreCase(signerType)) {
        try {
            signerConf = canonicalizeSignerConf(signerType, signerConf, new X509Certificate[] { caCert }, securityFactory);
        } catch (Exception ex) {
            throw new CaMgmtException(concat(ex.getClass().getName(), ": ", ex.getMessage()), ex);
        }
    }
    X509CaUris caUris = new X509CaUris(caCertUris, ocspUris, crlUris, deltaCrlUris);
    String name = caEntry.getIdent().getName();
    long nextCrlNumber = caEntry.getNextCrlNumber();
    CaStatus status = caEntry.getStatus();
    X509CaEntry entry = new X509CaEntry(new NameId(null, name), caEntry.getSerialNoBitLen(), nextCrlNumber, signerType, signerConf, caUris, numCrls, expirationPeriod);
    entry.setCert(caCert);
    entry.setCmpControlName(caEntry.getCmpControlName());
    entry.setCrlSignerName(caEntry.getCrlSignerName());
    entry.setDuplicateKeyPermitted(caEntry.isDuplicateKeyPermitted());
    entry.setDuplicateSubjectPermitted(caEntry.isDuplicateSubjectPermitted());
    entry.setExtraControl(caEntry.getExtraControl());
    entry.setKeepExpiredCertInDays(caEntry.getKeepExpiredCertInDays());
    entry.setMaxValidity(caEntry.getMaxValidity());
    entry.setPermission(caEntry.getPermission());
    entry.setResponderName(caEntry.getResponderName());
    entry.setSaveRequest(caEntry.isSaveRequest());
    entry.setStatus(status);
    entry.setValidityMode(caEntry.getValidityMode());
    addCa(entry);
    return caCert;
}
Also used : NameId(org.xipki.ca.api.NameId) InvalidConfException(org.xipki.common.InvalidConfException) CaStatus(org.xipki.ca.server.mgmt.api.CaStatus) 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) X509Certificate(java.security.cert.X509Certificate) CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) X509CaUris(org.xipki.ca.server.mgmt.api.x509.X509CaUris) GenerateSelfSignedResult(org.xipki.ca.server.impl.X509SelfSignedCertBuilder.GenerateSelfSignedResult) BigInteger(java.math.BigInteger) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) OperationException(org.xipki.ca.api.OperationException) X509CaEntry(org.xipki.ca.server.mgmt.api.x509.X509CaEntry)

Example 4 with CertificationRequest

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

the class EnrollCertCmd method execute0.

@Override
protected Object execute0() throws Exception {
    ScepClient client = getScepClient();
    CertificationRequest csr = CertificationRequest.getInstance(IoUtil.read(csrFile));
    EnrolmentResponse resp;
    PrivateKey key0 = getIdentityKey();
    X509Certificate cert0 = getIdentityCert();
    if (StringUtil.isBlank(method)) {
        resp = client.scepEnrol(csr, key0, cert0);
    } else if ("pkcs".equalsIgnoreCase(method)) {
        resp = client.scepPkcsReq(csr, key0, cert0);
    } else if ("renewal".equalsIgnoreCase(method)) {
        resp = client.scepRenewalReq(csr, key0, cert0);
    } else if ("update".equalsIgnoreCase(method)) {
        resp = client.scepUpdateReq(csr, key0, cert0);
    } else {
        throw new CmdFailure("invalid enroll method");
    }
    if (resp.isFailure()) {
        throw new CmdFailure("server returned 'failure'");
    }
    if (resp.isPending()) {
        throw new CmdFailure("server returned 'pending'");
    }
    X509Certificate cert = resp.getCertificates().get(0);
    saveVerbose("saved enrolled certificate to file", new File(outputFile), cert.getEncoded());
    return null;
}
Also used : PrivateKey(java.security.PrivateKey) CmdFailure(org.xipki.console.karaf.CmdFailure) ScepClient(org.xipki.scep.client.ScepClient) EnrolmentResponse(org.xipki.scep.client.EnrolmentResponse) File(java.io.File) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) X509Certificate(java.security.cert.X509Certificate)

Example 5 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest 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)

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