Search in sources :

Example 41 with Request

use of org.bouncycastle.asn1.ocsp.Request in project xipki by xipki.

the class X509CmpRequestor method envelope.

public PKIMessage envelope(CertRequest req, ProofOfPossession pop, String profileName) throws CmpRequestorException {
    ParamUtil.requireNonNull("req", req);
    ParamUtil.requireNonNull("pop", pop);
    ParamUtil.requireNonNull("profileName", profileName);
    PKIMessage request = buildPkiMessage(req, pop, profileName);
    return sign(request);
}
Also used : PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage)

Example 42 with Request

use of org.bouncycastle.asn1.ocsp.Request in project xipki by xipki.

the class X509CmpRequestor method buildUnrevokeOrRemoveCertRequest.

// method buildRevokeCertRequest
private PKIMessage buildUnrevokeOrRemoveCertRequest(UnrevokeOrRemoveCertRequest request, int reasonCode) throws CmpRequestorException {
    PKIHeader header = buildPkiHeader(null);
    List<UnrevokeOrRemoveCertEntry> requestEntries = request.getRequestEntries();
    List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
    for (UnrevokeOrRemoveCertEntry requestEntry : requestEntries) {
        CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
        certTempBuilder.setIssuer(requestEntry.getIssuer());
        certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
        byte[] aki = requestEntry.getAuthorityKeyIdentifier();
        if (aki != null) {
            Extensions certTempExts = getCertTempExtensions(aki);
            certTempBuilder.setExtensions(certTempExts);
        }
        Extension[] extensions = new Extension[1];
        try {
            ASN1Enumerated reason = new ASN1Enumerated(reasonCode);
            extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded()));
        } catch (IOException ex) {
            throw new CmpRequestorException(ex.getMessage(), ex);
        }
        Extensions exts = new Extensions(extensions);
        RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
        revDetailsArray.add(revDetails);
    }
    RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
    PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
    return new PKIMessage(header, body);
}
Also used : PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) ArrayList(java.util.ArrayList) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) RevReqContent(org.bouncycastle.asn1.cmp.RevReqContent) DEROctetString(org.bouncycastle.asn1.DEROctetString) Extension(org.bouncycastle.asn1.x509.Extension) CertTemplateBuilder(org.bouncycastle.asn1.crmf.CertTemplateBuilder) ASN1Enumerated(org.bouncycastle.asn1.ASN1Enumerated) UnrevokeOrRemoveCertEntry(org.xipki.ca.client.api.dto.UnrevokeOrRemoveCertEntry) RevDetails(org.bouncycastle.asn1.cmp.RevDetails)

Example 43 with Request

use of org.bouncycastle.asn1.ocsp.Request in project xipki by xipki.

the class X509CmpRequestor method removeCertificate.

public RevokeCertResultType removeCertificate(UnrevokeOrRemoveCertRequest request, RequestResponseDebug debug) throws CmpRequestorException, PkiErrorException {
    ParamUtil.requireNonNull("request", request);
    PKIMessage reqMessage = buildUnrevokeOrRemoveCertRequest(request, XiSecurityConstants.CMP_CRL_REASON_REMOVE);
    PkiResponse response = signAndSend(reqMessage, debug);
    return parse(response, request.getRequestEntries());
}
Also used : PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) PkiResponse(org.xipki.cmp.PkiResponse)

Example 44 with Request

use of org.bouncycastle.asn1.ocsp.Request in project xipki by xipki.

the class CaCertStoreDbImporter method importToDb.

public void importToDb() throws Exception {
    CertStoreType certstore;
    try {
        @SuppressWarnings("unchecked") JAXBElement<CertStoreType> root = (JAXBElement<CertStoreType>) unmarshaller.unmarshal(new File(baseDir, FILENAME_CA_CERTSTORE));
        certstore = root.getValue();
    } catch (JAXBException ex) {
        throw XmlUtil.convert(ex);
    }
    if (certstore.getVersion() > VERSION) {
        throw new Exception("could not import CertStore greater than " + VERSION + ": " + certstore.getVersion());
    }
    File processLogFile = new File(baseDir, DbPorter.IMPORT_PROCESS_LOG_FILENAME);
    System.out.println("importing CA certstore to database");
    try {
        if (!resume) {
            dropIndexes();
        }
        CaDbEntryType typeProcessedInLastProcess = null;
        Integer numProcessedInLastProcess = null;
        Long idProcessedInLastProcess = null;
        if (processLogFile.exists()) {
            byte[] content = IoUtil.read(processLogFile);
            if (content != null && content.length > 5) {
                String str = new String(content);
                StringTokenizer st = new StringTokenizer(str, ":");
                String type = st.nextToken();
                typeProcessedInLastProcess = CaDbEntryType.valueOf(type);
                numProcessedInLastProcess = Integer.parseInt(st.nextToken());
                idProcessedInLastProcess = Long.parseLong(st.nextToken());
            }
        }
        boolean entriesFinished = false;
        // finished for the given type
        if (typeProcessedInLastProcess != null && (idProcessedInLastProcess != null && idProcessedInLastProcess == -1)) {
            numProcessedInLastProcess = 0;
            idProcessedInLastProcess = 0L;
            switch(typeProcessedInLastProcess) {
                case CRL:
                    typeProcessedInLastProcess = CaDbEntryType.CERT;
                    break;
                case CERT:
                    typeProcessedInLastProcess = CaDbEntryType.REQUEST;
                    break;
                case REQUEST:
                    typeProcessedInLastProcess = CaDbEntryType.REQCERT;
                    break;
                case REQCERT:
                    entriesFinished = true;
                    break;
                default:
                    throw new RuntimeException("unsupported CaDbEntryType " + typeProcessedInLastProcess);
            }
        }
        if (!entriesFinished) {
            Exception exception = null;
            if (CaDbEntryType.CRL == typeProcessedInLastProcess || typeProcessedInLastProcess == null) {
                exception = importEntries(CaDbEntryType.CRL, certstore, processLogFile, numProcessedInLastProcess, idProcessedInLastProcess);
                typeProcessedInLastProcess = null;
                numProcessedInLastProcess = null;
                idProcessedInLastProcess = null;
            }
            CaDbEntryType[] types = { CaDbEntryType.CERT, CaDbEntryType.REQUEST, CaDbEntryType.REQCERT };
            for (CaDbEntryType type : types) {
                if (exception == null && (type == typeProcessedInLastProcess || typeProcessedInLastProcess == null)) {
                    exception = importEntries(type, certstore, processLogFile, numProcessedInLastProcess, idProcessedInLastProcess);
                }
            }
            if (exception != null) {
                throw exception;
            }
        }
        importPublishQueue(certstore.getPublishQueue());
        importDeltaCrlCache(certstore.getDeltaCRLCache());
        recoverIndexes();
        processLogFile.delete();
    } catch (Exception ex) {
        System.err.println("could not import CA certstore to database");
        throw ex;
    }
    System.out.println(" imported CA certstore to database");
}
Also used : JAXBException(javax.xml.bind.JAXBException) JAXBElement(javax.xml.bind.JAXBElement) DEROctetString(org.bouncycastle.asn1.DEROctetString) XMLStreamException(javax.xml.stream.XMLStreamException) DataAccessException(org.xipki.datasource.DataAccessException) JAXBException(javax.xml.bind.JAXBException) InvalidDataObjectException(org.xipki.ca.dbtool.xmlio.InvalidDataObjectException) CRLException(java.security.cert.CRLException) SQLException(java.sql.SQLException) CertificateException(java.security.cert.CertificateException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) BigInteger(java.math.BigInteger) StringTokenizer(java.util.StringTokenizer) CertStoreType(org.xipki.ca.dbtool.jaxb.ca.CertStoreType) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 45 with Request

use of org.bouncycastle.asn1.ocsp.Request in project xipki by xipki.

the class CaCertStoreDbImporter method importEntries.

private long importEntries(CaDbEntryType type, String entriesZipFile, long minId, File processLogFile, ProcessLog processLog, int numProcessedInLastProcess, PreparedStatement[] statements, String[] sqls) throws Exception {
    final int numEntriesPerCommit = Math.max(1, Math.round(type.getSqlBatchFactor() * numCertsPerCommit));
    ZipFile zipFile = new ZipFile(new File(entriesZipFile));
    ZipEntry entriesXmlEntry = zipFile.getEntry("overview.xml");
    DbiXmlReader entries;
    try {
        entries = createReader(type, zipFile.getInputStream(entriesXmlEntry));
    } catch (Exception ex) {
        try {
            zipFile.close();
        } catch (Exception e2) {
            LOG.error("could not close ZIP file {}: {}", entriesZipFile, e2.getMessage());
            LOG.debug("could not close ZIP file " + entriesZipFile, e2);
        }
        throw ex;
    }
    disableAutoCommit();
    try {
        int numEntriesInBatch = 0;
        long lastSuccessfulEntryId = 0;
        while (entries.hasNext()) {
            if (stopMe.get()) {
                throw new InterruptedException("interrupted by the user");
            }
            IdentifidDbObjectType entry = (IdentifidDbObjectType) entries.next();
            long id = entry.getId();
            if (id < minId) {
                continue;
            }
            numEntriesInBatch++;
            if (CaDbEntryType.CERT == type) {
                CertType cert = (CertType) entry;
                int certArt = (cert.getArt() == null) ? 1 : cert.getArt();
                String filename = cert.getFile();
                // rawcert
                ZipEntry certZipEnty = zipFile.getEntry(filename);
                // rawcert
                byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty));
                TBSCertificate tbsCert;
                try {
                    Certificate cc = Certificate.getInstance(encodedCert);
                    tbsCert = cc.getTBSCertificate();
                } catch (RuntimeException ex) {
                    LOG.error("could not parse certificate in file {}", filename);
                    LOG.debug("could not parse certificate in file " + filename, ex);
                    throw new CertificateException(ex.getMessage(), ex);
                }
                byte[] encodedKey = tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
                String b64Sha1FpCert = HashAlgo.SHA1.base64Hash(encodedCert);
                // cert
                String subjectText = X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen);
                PreparedStatement psCert = statements[0];
                PreparedStatement psRawcert = statements[1];
                try {
                    int idx = 1;
                    psCert.setLong(idx++, id);
                    psCert.setInt(idx++, certArt);
                    psCert.setLong(idx++, cert.getUpdate());
                    psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16));
                    psCert.setString(idx++, subjectText);
                    long fpSubject = X509Util.fpCanonicalizedName(tbsCert.getSubject());
                    psCert.setLong(idx++, fpSubject);
                    if (cert.getFpRs() != null) {
                        psCert.setLong(idx++, cert.getFpRs());
                    } else {
                        psCert.setNull(idx++, Types.BIGINT);
                    }
                    psCert.setLong(idx++, tbsCert.getStartDate().getDate().getTime() / 1000);
                    psCert.setLong(idx++, tbsCert.getEndDate().getDate().getTime() / 1000);
                    setBoolean(psCert, idx++, cert.getRev());
                    setInt(psCert, idx++, cert.getRr());
                    setLong(psCert, idx++, cert.getRt());
                    setLong(psCert, idx++, cert.getRit());
                    setInt(psCert, idx++, cert.getPid());
                    setInt(psCert, idx++, cert.getCaId());
                    setInt(psCert, idx++, cert.getRid());
                    setInt(psCert, idx++, cert.getUid());
                    psCert.setLong(idx++, FpIdCalculator.hash(encodedKey));
                    Extension extension = tbsCert.getExtensions().getExtension(Extension.basicConstraints);
                    boolean ee = true;
                    if (extension != null) {
                        ASN1Encodable asn1 = extension.getParsedValue();
                        ee = !BasicConstraints.getInstance(asn1).isCA();
                    }
                    psCert.setInt(idx++, ee ? 1 : 0);
                    psCert.setInt(idx++, cert.getReqType());
                    String tidS = null;
                    if (cert.getTid() != null) {
                        tidS = cert.getTid();
                    }
                    psCert.setString(idx++, tidS);
                    psCert.addBatch();
                } catch (SQLException ex) {
                    throw translate(SQL_ADD_CERT, ex);
                }
                try {
                    int idx = 1;
                    psRawcert.setLong(idx++, cert.getId());
                    psRawcert.setString(idx++, b64Sha1FpCert);
                    psRawcert.setString(idx++, cert.getRs());
                    psRawcert.setString(idx++, Base64.encodeToString(encodedCert));
                    psRawcert.addBatch();
                } catch (SQLException ex) {
                    throw translate(SQL_ADD_CRAW, ex);
                }
            } else if (CaDbEntryType.CRL == type) {
                PreparedStatement psAddCrl = statements[0];
                CrlType crl = (CrlType) entry;
                String filename = crl.getFile();
                // CRL
                ZipEntry zipEnty = zipFile.getEntry(filename);
                // rawcert
                byte[] encodedCrl = IoUtil.read(zipFile.getInputStream(zipEnty));
                X509CRL x509crl = null;
                try {
                    x509crl = X509Util.parseCrl(encodedCrl);
                } catch (Exception ex) {
                    LOG.error("could not parse CRL in file {}", filename);
                    LOG.debug("could not parse CRL in file " + filename, ex);
                    if (ex instanceof CRLException) {
                        throw (CRLException) ex;
                    } else {
                        throw new CRLException(ex.getMessage(), ex);
                    }
                }
                try {
                    byte[] octetString = x509crl.getExtensionValue(Extension.cRLNumber.getId());
                    if (octetString == null) {
                        LOG.warn("CRL without CRL number, ignore it");
                        continue;
                    }
                    byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
                    // CHECKSTYLE:SKIP
                    BigInteger crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
                    BigInteger baseCrlNumber = null;
                    octetString = x509crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
                    if (octetString != null) {
                        extnValue = DEROctetString.getInstance(octetString).getOctets();
                        baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
                    }
                    int idx = 1;
                    psAddCrl.setLong(idx++, crl.getId());
                    psAddCrl.setInt(idx++, crl.getCaId());
                    psAddCrl.setLong(idx++, crlNumber.longValue());
                    psAddCrl.setLong(idx++, x509crl.getThisUpdate().getTime() / 1000);
                    if (x509crl.getNextUpdate() != null) {
                        psAddCrl.setLong(idx++, x509crl.getNextUpdate().getTime() / 1000);
                    } else {
                        psAddCrl.setNull(idx++, Types.INTEGER);
                    }
                    if (baseCrlNumber == null) {
                        setBoolean(psAddCrl, idx++, false);
                        psAddCrl.setNull(idx++, Types.BIGINT);
                    } else {
                        setBoolean(psAddCrl, idx++, true);
                        psAddCrl.setLong(idx++, baseCrlNumber.longValue());
                    }
                    String str = Base64.encodeToString(encodedCrl);
                    psAddCrl.setString(idx++, str);
                    psAddCrl.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import CRL with ID=" + crl.getId() + ", message: " + ex.getMessage());
                    throw ex;
                }
            } else if (CaDbEntryType.REQUEST == type) {
                PreparedStatement psAddRequest = statements[0];
                RequestType request = (RequestType) entry;
                String filename = request.getFile();
                ZipEntry zipEnty = zipFile.getEntry(filename);
                byte[] encodedRequest = IoUtil.read(zipFile.getInputStream(zipEnty));
                try {
                    int idx = 1;
                    psAddRequest.setLong(idx++, request.getId());
                    psAddRequest.setLong(idx++, request.getUpdate());
                    psAddRequest.setString(idx++, Base64.encodeToString(encodedRequest));
                    psAddRequest.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import REQUEST with ID=" + request.getId() + ", message: " + ex.getMessage());
                    throw ex;
                }
            } else if (CaDbEntryType.REQCERT == type) {
                PreparedStatement psAddReqCert = statements[0];
                RequestCertType reqCert = (RequestCertType) entry;
                try {
                    int idx = 1;
                    psAddReqCert.setLong(idx++, reqCert.getId());
                    psAddReqCert.setLong(idx++, reqCert.getRid());
                    psAddReqCert.setLong(idx++, reqCert.getCid());
                    psAddReqCert.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import REQUEST with ID=" + reqCert.getId() + ", message: " + ex.getMessage());
                    throw ex;
                }
            } else {
                throw new RuntimeException("Unknown CaDbEntryType " + type);
            }
            boolean isLastBlock = !entries.hasNext();
            if (numEntriesInBatch > 0 && (numEntriesInBatch % numEntriesPerCommit == 0 || isLastBlock)) {
                if (evaulateOnly) {
                    for (PreparedStatement m : statements) {
                        m.clearBatch();
                    }
                } else {
                    String sql = null;
                    try {
                        for (int i = 0; i < sqls.length; i++) {
                            sql = sqls[i];
                            statements[i].executeBatch();
                        }
                        sql = null;
                        commit("(commit import to CA)");
                    } catch (Throwable th) {
                        rollback();
                        deleteFromTableWithLargerId(type.getTableName(), "ID", id, LOG);
                        if (CaDbEntryType.CERT == type) {
                            deleteFromTableWithLargerId("CRAW", "CID", id, LOG);
                        }
                        if (th instanceof SQLException) {
                            throw translate(sql, (SQLException) th);
                        } else if (th instanceof Exception) {
                            throw (Exception) th;
                        } else {
                            throw new Exception(th);
                        }
                    }
                }
                lastSuccessfulEntryId = id;
                processLog.addNumProcessed(numEntriesInBatch);
                numEntriesInBatch = 0;
                echoToFile(type + ":" + (numProcessedInLastProcess + processLog.numProcessed()) + ":" + lastSuccessfulEntryId, processLogFile);
                processLog.printStatus();
            }
        }
        return lastSuccessfulEntryId;
    } finally {
        recoverAutoCommit();
        zipFile.close();
    }
}
Also used : X509CRL(java.security.cert.X509CRL) SQLException(java.sql.SQLException) ZipEntry(java.util.zip.ZipEntry) RequestCertType(org.xipki.ca.dbtool.xmlio.ca.RequestCertType) CertType(org.xipki.ca.dbtool.xmlio.ca.CertType) CertificateException(java.security.cert.CertificateException) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) CRLException(java.security.cert.CRLException) IdentifidDbObjectType(org.xipki.ca.dbtool.xmlio.IdentifidDbObjectType) DbiXmlReader(org.xipki.ca.dbtool.xmlio.DbiXmlReader) PreparedStatement(java.sql.PreparedStatement) RequestCertType(org.xipki.ca.dbtool.xmlio.ca.RequestCertType) XMLStreamException(javax.xml.stream.XMLStreamException) DataAccessException(org.xipki.datasource.DataAccessException) JAXBException(javax.xml.bind.JAXBException) InvalidDataObjectException(org.xipki.ca.dbtool.xmlio.InvalidDataObjectException) CRLException(java.security.cert.CRLException) SQLException(java.sql.SQLException) CertificateException(java.security.cert.CertificateException) Extension(org.bouncycastle.asn1.x509.Extension) ZipFile(java.util.zip.ZipFile) CrlType(org.xipki.ca.dbtool.xmlio.ca.CrlType) BigInteger(java.math.BigInteger) ZipFile(java.util.zip.ZipFile) File(java.io.File) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) RequestType(org.xipki.ca.dbtool.xmlio.ca.RequestType)

Aggregations

IOException (java.io.IOException)47 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)30 Date (java.util.Date)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)26 BigInteger (java.math.BigInteger)23 X509Certificate (java.security.cert.X509Certificate)22 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)22 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)20 CertificateException (java.security.cert.CertificateException)18 ArrayList (java.util.ArrayList)17 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)17 X500Name (org.bouncycastle.asn1.x500.X500Name)16 Extension (org.bouncycastle.asn1.x509.Extension)16 Extensions (org.bouncycastle.asn1.x509.Extensions)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)15 DERIA5String (org.bouncycastle.asn1.DERIA5String)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 PKIBody (org.bouncycastle.asn1.cmp.PKIBody)13 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)12 GeneralName (org.bouncycastle.asn1.x509.GeneralName)11