Example usage for org.bouncycastle.asn1.x509 Certificate getTBSCertificate

List of usage examples for org.bouncycastle.asn1.x509 Certificate getTBSCertificate

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Certificate getTBSCertificate.

Prototype

public TBSCertificate getTBSCertificate() 

Source Link

Usage

From source file:org.xipki.dbtool.OcspCertStoreDbImporter.java

License:Open Source License

private void import_issuer(final Issuers issuers) throws DataAccessException, CertificateException {
    System.out.println("importing table ISSUER");
    PreparedStatement ps = prepareStatement(SQL_ADD_CAINFO);

    try {/*  www.jav a  2s  . c  om*/
        for (IssuerType issuer : issuers.getIssuer()) {
            try {
                String b64Cert = issuer.getCert();
                byte[] encodedCert = Base64.decode(b64Cert);

                Certificate c;
                byte[] encodedName;
                try {
                    c = Certificate.getInstance(encodedCert);
                    encodedName = c.getSubject().getEncoded("DER");
                } catch (Exception e) {
                    LOG.error("could not parse certificate of issuer {}", issuer.getId());
                    LOG.debug("could not parse certificate of issuer " + issuer.getId(), e);
                    if (e instanceof CertificateException) {
                        throw (CertificateException) e;
                    } else {
                        throw new CertificateException(e.getMessage(), e);
                    }
                }
                byte[] encodedKey = c.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

                int idx = 1;
                ps.setInt(idx++, issuer.getId());
                ps.setString(idx++, X509Util.getRFC4519Name(c.getSubject()));
                ps.setLong(idx++, c.getTBSCertificate().getStartDate().getDate().getTime() / 1000);
                ps.setLong(idx++, c.getTBSCertificate().getEndDate().getDate().getTime() / 1000);
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA224, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA224, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA256, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA256, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA384, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA384, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA512, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA512, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedCert));
                ps.setString(idx++, b64Cert);
                setBoolean(ps, idx++, issuer.isRevoked());
                setInt(ps, idx++, issuer.getRevReason());
                setLong(ps, idx++, issuer.getRevTime());
                setLong(ps, idx++, issuer.getRevInvTime());

                ps.execute();
            } catch (SQLException e) {
                System.err.println("error while importing issuer with id=" + issuer.getId());
                throw translate(SQL_ADD_CAINFO, e);
            } catch (CertificateException e) {
                System.err.println("error while importing issuer with id=" + issuer.getId());
                throw e;
            }
        }
    } finally {
        releaseResources(ps, null);
    }
    System.out.println(" imported table ISSUER");
}

From source file:org.xipki.dbtool.OcspCertStoreFromCaDbImporter.java

License:Open Source License

private List<Integer> import_issuer(final Cas issuers, final List<CaType> cas)
        throws DataAccessException, CertificateException {
    System.out.println("importing table ISSUER");
    final String sql = OcspCertStoreDbImporter.SQL_ADD_CAINFO;
    PreparedStatement ps = prepareStatement(sql);

    List<Integer> relatedCaIds = new LinkedList<>();

    try {//from   w ww  . j a  va 2s . co m
        for (CertstoreCaType issuer : issuers.getCa()) {
            try {
                String b64Cert = issuer.getCert();
                byte[] encodedCert = Base64.decode(b64Cert);

                // retrieve the revocation information of the CA, if possible
                CaType ca = null;
                for (CaType caType : cas) {
                    if (Arrays.equals(encodedCert, Base64.decode(caType.getCert()))) {
                        ca = caType;
                        break;
                    }
                }

                if (ca == null) {
                    continue;
                }

                relatedCaIds.add(issuer.getId());

                Certificate c;
                byte[] encodedName;
                try {
                    c = Certificate.getInstance(encodedCert);
                    encodedName = c.getSubject().getEncoded("DER");
                } catch (Exception e) {
                    LOG.error("could not parse certificate of issuer {}", issuer.getId());
                    LOG.debug("could not parse certificate of issuer " + issuer.getId(), e);
                    if (e instanceof CertificateException) {
                        throw (CertificateException) e;
                    } else {
                        throw new CertificateException(e.getMessage(), e);
                    }
                }
                byte[] encodedKey = c.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

                int idx = 1;
                ps.setInt(idx++, issuer.getId());
                ps.setString(idx++, X509Util.getRFC4519Name(c.getSubject()));
                ps.setLong(idx++, c.getTBSCertificate().getStartDate().getDate().getTime() / 1000);
                ps.setLong(idx++, c.getTBSCertificate().getEndDate().getDate().getTime() / 1000);
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA224, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA224, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA256, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA256, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA384, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA384, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA512, encodedName));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA512, encodedKey));
                ps.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedCert));
                ps.setString(idx++, b64Cert);

                setBoolean(ps, idx++, ca.isRevoked());
                setInt(ps, idx++, ca.getRevReason());
                setLong(ps, idx++, ca.getRevTime());
                setLong(ps, idx++, ca.getRevInvTime());

                ps.execute();
            } catch (SQLException e) {
                System.err.println("error while importing issuer with id=" + issuer.getId());
                throw translate(sql, e);
            } catch (CertificateException e) {
                System.err.println("error while importing issuer with id=" + issuer.getId());
                throw e;
            }
        }
    } finally {
        releaseResources(ps, null);
    }

    System.out.println(" imported table ISSUER");
    return relatedCaIds;
}

From source file:org.xipki.pki.ca.dbtool.port.CaCertStoreDbImporter.java

License:Open Source License

private long doImportEntries(final CaDbEntryType type, final String entriesZipFile, final long minId,
        final File processLogFile, final ProcessLog processLog, final int numProcessedInLastProcess,
        final PreparedStatement[] statements, final 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;/* w w  w.  ja va2  s. c  o m*/
    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) {
                CaCertType cert = (CaCertType) 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 = HashAlgoType.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());
                    psCert.setString(idx++, cert.getUser());
                    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.toBase64String(encodedCert));
                    psRawcert.addBatch();
                } catch (SQLException ex) {
                    throw translate(SQL_ADD_CRAW, ex);
                }
            } else if (CaDbEntryType.CRL == type) {
                PreparedStatement psAddCrl = statements[0];

                CaCrlType crl = (CaCrlType) 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.toBase64String(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.USER == type) {
                PreparedStatement psAddUser = statements[0];
                CaUserType user = (CaUserType) entry;

                try {
                    int idx = 1;
                    psAddUser.setLong(idx++, user.getId());
                    psAddUser.setString(idx++, user.getName());
                    psAddUser.setString(idx++, user.getPassword());
                    psAddUser.setString(idx++, user.getCnRegex());
                    psAddUser.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import USERNAME with ID=" + user.getId() + ", message: "
                            + ex.getMessage());
                    throw ex;
                }
            } else if (CaDbEntryType.REQUEST == type) {
                PreparedStatement psAddRequest = statements[0];

                CaRequestType request = (CaRequestType) 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.toBase64String(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];

                CaRequestCertType reqCert = (CaRequestCertType) 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.getNumProcessed()) + ":"
                        + lastSuccessfulEntryId, processLogFile);
                processLog.printStatus();
            }

        } // end while

        return lastSuccessfulEntryId;
    } finally {
        recoverAutoCommit();
        zipFile.close();
    }
}

From source file:org.xipki.pki.ca.dbtool.port.OcspCertStoreDbImporter.java

License:Open Source License

private void doImportIssuer(final IssuerType issuer, final PreparedStatement ps)
        throws DataAccessException, CertificateException, IOException {
    try {/*from w w w. ja  va  2 s.  c o m*/
        String certFilename = issuer.getCertFile();
        String b64Cert = new String(IoUtil.read(new File(baseDir, certFilename)));
        byte[] encodedCert = Base64.decode(b64Cert);

        Certificate cert;
        try {
            cert = Certificate.getInstance(encodedCert);
        } catch (Exception ex) {
            LOG.error("could not parse certificate of issuer {}", issuer.getId());
            LOG.debug("could not parse certificate of issuer " + issuer.getId(), ex);
            if (ex instanceof CertificateException) {
                throw (CertificateException) ex;
            } else {
                throw new CertificateException(ex.getMessage(), ex);
            }
        }

        int idx = 1;
        ps.setInt(idx++, issuer.getId());
        ps.setString(idx++, X509Util.cutX500Name(cert.getSubject(), maxX500nameLen));
        ps.setLong(idx++, cert.getTBSCertificate().getStartDate().getDate().getTime() / 1000);
        ps.setLong(idx++, cert.getTBSCertificate().getEndDate().getDate().getTime() / 1000);
        ps.setString(idx++, sha1(encodedCert));
        setBoolean(ps, idx++, issuer.isRevoked());
        setInt(ps, idx++, issuer.getRevReason());
        setLong(ps, idx++, issuer.getRevTime());
        setLong(ps, idx++, issuer.getRevInvTime());
        ps.setString(idx++, b64Cert);

        ps.execute();
    } catch (SQLException ex) {
        System.err.println("could not import issuer with id=" + issuer.getId());
        throw translate(SQL_ADD_ISSUER, ex);
    } catch (CertificateException ex) {
        System.err.println("could not import issuer with id=" + issuer.getId());
        throw ex;
    }
}

From source file:org.xipki.pki.ca.dbtool.port.OcspCertStoreDbImporter.java

License:Open Source License

private long doImportCert(final PreparedStatement psCert, final PreparedStatement psCerthash,
        final PreparedStatement psRawcert, final String certsZipFile, final long minId,
        final File processLogFile, final ProcessLog processLog, final int numProcessedInLastProcess)
        throws Exception {
    ZipFile zipFile = new ZipFile(new File(certsZipFile));
    ZipEntry certsXmlEntry = zipFile.getEntry("certs.xml");

    OcspCertsReader certs;/*from w w w.  j a v  a2s.  c om*/
    try {
        certs = new OcspCertsReader(zipFile.getInputStream(certsXmlEntry));
    } catch (Exception ex) {
        try {
            zipFile.close();
        } catch (Exception e2) {
            LOG.error("could not close ZIP file {}: {}", certsZipFile, e2.getMessage());
            LOG.debug("could not close ZIP file " + certsZipFile, e2);
        }
        throw ex;
    }

    disableAutoCommit();

    try {
        int numEntriesInBatch = 0;
        long lastSuccessfulCertId = 0;

        while (certs.hasNext()) {
            if (stopMe.get()) {
                throw new InterruptedException("interrupted by the user");
            }

            OcspCertType cert = (OcspCertType) certs.next();

            long id = cert.getId();
            if (id < minId) {
                continue;
            }

            numEntriesInBatch++;
            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);
            }

            // cert
            try {
                int idx = 1;
                psCert.setLong(idx++, id);
                psCert.setInt(idx++, cert.getIid());
                psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16));
                psCert.setLong(idx++, cert.getUpdate());
                psCert.setLong(idx++, tbsCert.getStartDate().getDate().getTime() / 1000);
                psCert.setLong(idx++, tbsCert.getEndDate().getDate().getTime() / 1000);
                setBoolean(psCert, idx++, cert.getRev().booleanValue());
                setInt(psCert, idx++, cert.getRr());
                setLong(psCert, idx++, cert.getRt());
                setLong(psCert, idx++, cert.getRit());
                psCert.setString(idx++, cert.getProfile());
                psCert.addBatch();
            } catch (SQLException ex) {
                throw translate(SQL_ADD_CERT, ex);
            }

            // certhash
            try {
                int idx = 1;
                psCerthash.setLong(idx++, cert.getId());
                psCerthash.setString(idx++, sha1(encodedCert));
                psCerthash.setString(idx++, sha224(encodedCert));
                psCerthash.setString(idx++, sha256(encodedCert));
                psCerthash.setString(idx++, sha384(encodedCert));
                psCerthash.setString(idx++, sha512(encodedCert));
                psCerthash.addBatch();
            } catch (SQLException ex) {
                throw translate(SQL_ADD_CHASH, ex);
            }

            // rawcert
            try {
                int idx = 1;
                psRawcert.setLong(idx++, cert.getId());
                psRawcert.setString(idx++, X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen));
                psRawcert.setString(idx++, Base64.toBase64String(encodedCert));
                psRawcert.addBatch();
            } catch (SQLException ex) {
                throw translate(SQL_ADD_CRAW, ex);
            }

            boolean isLastBlock = !certs.hasNext();

            if (numEntriesInBatch > 0 && (numEntriesInBatch % this.numCertsPerCommit == 0 || isLastBlock)) {
                if (evaulateOnly) {
                    psCert.clearBatch();
                    psCerthash.clearBatch();
                    psRawcert.clearBatch();
                } else {
                    String sql = null;
                    try {
                        sql = SQL_ADD_CERT;
                        psCert.executeBatch();

                        sql = SQL_ADD_CHASH;
                        psCerthash.executeBatch();

                        sql = SQL_ADD_CRAW;
                        psRawcert.executeBatch();

                        sql = null;
                        commit("(commit import cert to OCSP)");
                    } catch (Throwable th) {
                        rollback();
                        deleteCertGreatherThan(lastSuccessfulCertId, LOG);
                        if (th instanceof SQLException) {
                            throw translate(sql, (SQLException) th);
                        } else if (th instanceof Exception) {
                            throw (Exception) th;
                        } else {
                            throw new Exception(th);
                        }
                    }
                }

                lastSuccessfulCertId = id;
                processLog.addNumProcessed(numEntriesInBatch);
                numEntriesInBatch = 0;
                echoToFile(
                        (numProcessedInLastProcess + processLog.getNumProcessed()) + ":" + lastSuccessfulCertId,
                        processLogFile);
                processLog.printStatus();
            }
        } // end for

        return lastSuccessfulCertId;
    } finally {
        recoverAutoCommit();
        zipFile.close();
    }
}

From source file:org.xipki.pki.ca.dbtool.port.OcspCertStoreFromCaDbImporter.java

License:Open Source License

private void doImportIssuer(final CertstoreCaType issuer, final String sql, final PreparedStatement ps,
        final List<CaType> cas, final List<Integer> relatedCaIds)
        throws IOException, DataAccessException, CertificateException {
    try {//from  w w w .  j  ava  2s  . c o m
        byte[] encodedCert = getBinary(issuer.getCert());

        // retrieve the revocation information of the CA, if possible
        CaType ca = null;
        for (CaType caType : cas) {
            if (Arrays.equals(encodedCert, getBinary(caType.getCert()))) {
                ca = caType;
                break;
            }
        }

        if (ca == null) {
            return;
        }

        relatedCaIds.add(issuer.getId());

        Certificate cert;
        try {
            cert = Certificate.getInstance(encodedCert);
        } catch (Exception ex) {
            String msg = "could not parse certificate of issuer " + issuer.getId();
            LogUtil.error(LOG, ex, msg);
            if (ex instanceof CertificateException) {
                throw (CertificateException) ex;
            } else {
                throw new CertificateException(ex.getMessage(), ex);
            }
        }

        int idx = 1;
        ps.setInt(idx++, issuer.getId());
        ps.setString(idx++, X509Util.cutX500Name(cert.getSubject(), maxX500nameLen));
        ps.setLong(idx++, cert.getTBSCertificate().getStartDate().getDate().getTime() / 1000);
        ps.setLong(idx++, cert.getTBSCertificate().getEndDate().getDate().getTime() / 1000);
        ps.setString(idx++, HashAlgoType.SHA1.base64Hash(encodedCert));
        setBoolean(ps, idx++, ca.isRevoked());
        setInt(ps, idx++, ca.getRevReason());
        setLong(ps, idx++, ca.getRevTime());
        setLong(ps, idx++, ca.getRevInvTime());
        ps.setString(idx++, Base64.toBase64String(encodedCert));

        ps.execute();
    } catch (SQLException ex) {
        System.err.println("could not import issuer with id=" + issuer.getId());
        throw translate(sql, ex);
    } catch (CertificateException ex) {
        System.err.println("could not import issuer with id=" + issuer.getId());
        throw ex;
    }
}

From source file:org.xipki.pki.ca.dbtool.port.OcspCertStoreFromCaDbImporter.java

License:Open Source License

private long doImportCert(final ImportStatements statments, final String certsZipFile,
        final Map<Integer, String> profileMap, final boolean revokedOnly, final List<Integer> caIds,
        final long minId, final File processLogFile, final ProcessLog processLog,
        final int numProcessedInLastProcess, final ProcessLog importLog) throws Exception {
    ZipFile zipFile = new ZipFile(new File(certsZipFile));
    ZipEntry certsXmlEntry = zipFile.getEntry("overview.xml");

    CaCertsReader certs;//from   ww w  .j  a v  a  2s .c  om
    try {
        certs = new CaCertsReader(zipFile.getInputStream(certsXmlEntry));
    } catch (Exception ex) {
        try {
            zipFile.close();
        } catch (Exception ex2) {
            LOG.error("could not close ZIP file {}: {}", certsZipFile, ex2.getMessage());
            LOG.debug("could not close ZIP file " + certsZipFile, ex2);
        }
        throw ex;
    }

    disableAutoCommit();

    PreparedStatement psCert = statments.psCert;
    PreparedStatement psCerthash = statments.psCerthash;
    PreparedStatement psRawCert = statments.psRawCert;

    try {
        int numProcessedEntriesInBatch = 0;
        int numImportedEntriesInBatch = 0;
        long lastSuccessfulCertId = 0;

        while (certs.hasNext()) {
            if (stopMe.get()) {
                throw new InterruptedException("interrupted by the user");
            }

            CaCertType cert = (CaCertType) certs.next();

            long id = cert.getId();
            lastSuccessfulCertId = id;
            if (id < minId) {
                continue;
            }

            numProcessedEntriesInBatch++;

            if (!revokedOnly || cert.getRev().booleanValue()) {
                int caId = cert.getCaId();
                if (caIds.contains(caId)) {
                    numImportedEntriesInBatch++;

                    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);
                    }

                    // cert
                    try {
                        int idx = 1;
                        psCert.setLong(idx++, id);
                        psCert.setInt(idx++, caId);
                        psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16));
                        psCert.setLong(idx++, cert.getUpdate());
                        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());

                        int certprofileId = cert.getPid();
                        String certprofileName = profileMap.get(certprofileId);
                        psCert.setString(idx++, certprofileName);
                        psCert.addBatch();
                    } catch (SQLException ex) {
                        throw translate(SQL_ADD_CERT, ex);
                    }

                    // certhash
                    try {
                        int idx = 1;
                        psCerthash.setLong(idx++, id);
                        psCerthash.setString(idx++, HashAlgoType.SHA1.base64Hash(encodedCert));
                        psCerthash.setString(idx++, HashAlgoType.SHA224.base64Hash(encodedCert));
                        psCerthash.setString(idx++, HashAlgoType.SHA256.base64Hash(encodedCert));
                        psCerthash.setString(idx++, HashAlgoType.SHA384.base64Hash(encodedCert));
                        psCerthash.setString(idx++, HashAlgoType.SHA512.base64Hash(encodedCert));
                        psCerthash.addBatch();
                    } catch (SQLException ex) {
                        throw translate(SQL_ADD_CHASH, ex);
                    }

                    // rawcert
                    try {
                        int idx = 1;
                        psRawCert.setLong(idx++, id);
                        psRawCert.setString(idx++, X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen));
                        psRawCert.setString(idx++, Base64.toBase64String(encodedCert));
                        psRawCert.addBatch();
                    } catch (SQLException ex) {
                        throw translate(SQL_ADD_CRAW, ex);
                    }
                } // end if (caIds.contains(caId))
            } // end if (revokedOnly

            boolean isLastBlock = !certs.hasNext();

            if (numImportedEntriesInBatch > 0
                    && (numImportedEntriesInBatch % this.numCertsPerCommit == 0 || isLastBlock)) {
                if (evaulateOnly) {
                    psCert.clearBatch();
                    psCerthash.clearBatch();
                    psRawCert.clearBatch();
                } else {
                    String sql = null;
                    try {
                        sql = SQL_ADD_CERT;
                        psCert.executeBatch();

                        sql = SQL_ADD_CHASH;
                        psCerthash.executeBatch();

                        sql = SQL_ADD_CRAW;
                        psRawCert.executeBatch();

                        sql = null;
                        commit("(commit import cert to OCSP)");
                    } catch (Throwable th) {
                        rollback();
                        deleteCertGreatherThan(lastSuccessfulCertId, LOG);
                        if (th instanceof SQLException) {
                            throw translate(sql, (SQLException) th);
                        } else if (th instanceof Exception) {
                            throw (Exception) th;
                        } else {
                            throw new Exception(th);
                        }
                    }
                }

                lastSuccessfulCertId = id;
                processLog.addNumProcessed(numProcessedEntriesInBatch);
                importLog.addNumProcessed(numImportedEntriesInBatch);
                numProcessedEntriesInBatch = 0;
                numImportedEntriesInBatch = 0;
                String filename = (numProcessedInLastProcess + processLog.getNumProcessed()) + ":"
                        + lastSuccessfulCertId;
                echoToFile(filename, processLogFile);
                processLog.printStatus();
            } else if (isLastBlock) {
                lastSuccessfulCertId = id;
                processLog.addNumProcessed(numProcessedEntriesInBatch);
                importLog.addNumProcessed(numImportedEntriesInBatch);
                numProcessedEntriesInBatch = 0;
                numImportedEntriesInBatch = 0;
                String filename = (numProcessedInLastProcess + processLog.getNumProcessed()) + ":"
                        + lastSuccessfulCertId;
                echoToFile(filename, processLogFile);
                processLog.printStatus();
            }
            // if (numImportedEntriesInBatch)
        } // end for

        return lastSuccessfulCertId;
    } finally {
        recoverAutoCommit();
        zipFile.close();
    }
}

From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java

License:Open Source License

public List<ValidationIssue> checkExtensions(final Certificate cert, final X509IssuerInfo issuerInfo,
        final Extensions requestedExtensions, final X500Name requestedSubject) {
    ParamUtil.requireNonNull("cert", cert);
    ParamUtil.requireNonNull("issuerInfo", issuerInfo);

    X509Certificate jceCert;//from   www .  j a  v a2  s .c o  m
    try {
        jceCert = X509Util.toX509Cert(cert);
    } catch (CertificateException ex) {
        throw new IllegalArgumentException("invalid cert: " + ex.getMessage());
    }

    List<ValidationIssue> result = new LinkedList<>();

    // detect the list of extension types in certificate
    Set<ASN1ObjectIdentifier> presentExtenionTypes = getExensionTypes(cert, issuerInfo, requestedExtensions);

    Extensions extensions = cert.getTBSCertificate().getExtensions();
    ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs();

    if (oids == null) {
        ValidationIssue issue = new ValidationIssue("X509.EXT.GEN", "extension general");
        result.add(issue);
        issue.setFailureMessage("no extension is present");
        return result;
    }

    List<ASN1ObjectIdentifier> certExtTypes = Arrays.asList(oids);

    for (ASN1ObjectIdentifier extType : presentExtenionTypes) {
        if (!certExtTypes.contains(extType)) {
            ValidationIssue issue = createExtensionIssue(extType);
            result.add(issue);
            issue.setFailureMessage("extension is absent but is required");
        }
    }

    Map<ASN1ObjectIdentifier, ExtensionControl> extensionControls = certProfile.getExtensionControls();
    for (ASN1ObjectIdentifier oid : certExtTypes) {
        ValidationIssue issue = createExtensionIssue(oid);
        result.add(issue);
        if (!presentExtenionTypes.contains(oid)) {
            issue.setFailureMessage("extension is present but is not permitted");
            continue;
        }

        Extension ext = extensions.getExtension(oid);
        StringBuilder failureMsg = new StringBuilder();
        ExtensionControl extControl = extensionControls.get(oid);

        if (extControl.isCritical() != ext.isCritical()) {
            addViolation(failureMsg, "critical", ext.isCritical(), extControl.isCritical());
        }

        byte[] extensionValue = ext.getExtnValue().getOctets();
        try {
            if (Extension.authorityKeyIdentifier.equals(oid)) {
                // AuthorityKeyIdentifier
                checkExtensionIssuerKeyIdentifier(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.subjectKeyIdentifier.equals(oid)) {
                // SubjectKeyIdentifier
                checkExtensionSubjectKeyIdentifier(failureMsg, extensionValue, cert.getSubjectPublicKeyInfo());
            } else if (Extension.keyUsage.equals(oid)) {
                // KeyUsage
                checkExtensionKeyUsage(failureMsg, extensionValue, jceCert.getKeyUsage(), requestedExtensions,
                        extControl);
            } else if (Extension.certificatePolicies.equals(oid)) {
                // CertificatePolicies
                checkExtensionCertificatePolicies(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.policyMappings.equals(oid)) {
                // Policy Mappings
                checkExtensionPolicyMappings(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.subjectAlternativeName.equals(oid)) {
                // SubjectAltName
                checkExtensionSubjectAltName(failureMsg, extensionValue, requestedExtensions, extControl,
                        requestedSubject);
            } else if (Extension.subjectDirectoryAttributes.equals(oid)) {
                // SubjectDirectoryAttributes
                checkExtensionSubjectDirAttrs(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.issuerAlternativeName.equals(oid)) {
                // IssuerAltName
                checkExtensionIssuerAltNames(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.basicConstraints.equals(oid)) {
                // Basic Constraints
                checkExtensionBasicConstraints(failureMsg, extensionValue);
            } else if (Extension.nameConstraints.equals(oid)) {
                // Name Constraints
                checkExtensionNameConstraints(failureMsg, extensionValue, extensions, extControl);
            } else if (Extension.policyConstraints.equals(oid)) {
                // PolicyConstrains
                checkExtensionPolicyConstraints(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.extendedKeyUsage.equals(oid)) {
                // ExtendedKeyUsage
                checkExtensionExtendedKeyUsage(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.cRLDistributionPoints.equals(oid)) {
                // CRL Distribution Points
                checkExtensionCrlDistributionPoints(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.inhibitAnyPolicy.equals(oid)) {
                // Inhibit anyPolicy
                checkExtensionInhibitAnyPolicy(failureMsg, extensionValue, extensions, extControl);
            } else if (Extension.freshestCRL.equals(oid)) {
                // Freshest CRL
                checkExtensionDeltaCrlDistributionPoints(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.authorityInfoAccess.equals(oid)) {
                // Authority Information Access
                checkExtensionAuthorityInfoAccess(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.subjectInfoAccess.equals(oid)) {
                // SubjectInfoAccess
                checkExtensionSubjectInfoAccess(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_extension_admission.equals(oid)) {
                // Admission
                checkExtensionAdmission(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_extension_pkix_ocsp_nocheck.equals(oid)) {
                // ocsp-nocheck
                checkExtensionOcspNocheck(failureMsg, extensionValue);
            } else if (ObjectIdentifiers.id_extension_restriction.equals(oid)) {
                // restriction
                checkExtensionRestriction(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_extension_additionalInformation.equals(oid)) {
                // additionalInformation
                checkExtensionAdditionalInformation(failureMsg, extensionValue, requestedExtensions,
                        extControl);
            } else if (ObjectIdentifiers.id_extension_validityModel.equals(oid)) {
                // validityModel
                checkExtensionValidityModel(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.privateKeyUsagePeriod.equals(oid)) {
                // privateKeyUsagePeriod
                checkExtensionPrivateKeyUsagePeriod(failureMsg, extensionValue, jceCert.getNotBefore(),
                        jceCert.getNotAfter());
            } else if (Extension.qCStatements.equals(oid)) {
                // qCStatements
                checkExtensionQcStatements(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.biometricInfo.equals(oid)) {
                // biometricInfo
                checkExtensionBiometricInfo(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_pe_tlsfeature.equals(oid)) {
                // tlsFeature
                checkExtensionTlsFeature(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_xipki_ext_authorizationTemplate.equals(oid)) {
                // authorizationTemplate
                checkExtensionAuthorizationTemplate(failureMsg, extensionValue, requestedExtensions,
                        extControl);
            } else {
                byte[] expected;
                if (ObjectIdentifiers.id_smimeCapabilities.equals(oid)) {
                    // SMIMECapabilities
                    expected = smimeCapabilities.getValue();
                } else {
                    expected = getExpectedExtValue(oid, requestedExtensions, extControl);
                }

                if (!Arrays.equals(expected, extensionValue)) {
                    addViolation(failureMsg, "extension valus", hex(extensionValue),
                            (expected == null) ? "not present" : hex(expected));
                }
            }

            if (failureMsg.length() > 0) {
                issue.setFailureMessage(failureMsg.toString());
            }

        } catch (IllegalArgumentException | ClassCastException | ArrayIndexOutOfBoundsException ex) {
            LOG.debug("extension value does not have correct syntax", ex);
            issue.setFailureMessage("extension value does not have correct syntax");
        }
    }

    return result;
}

From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java

License:Open Source License

private Set<ASN1ObjectIdentifier> getExensionTypes(final Certificate cert, final X509IssuerInfo issuerInfo,
        final Extensions requestedExtensions) {
    Set<ASN1ObjectIdentifier> types = new HashSet<>();
    // profile required extension types
    Map<ASN1ObjectIdentifier, ExtensionControl> extensionControls = certProfile.getExtensionControls();
    for (ASN1ObjectIdentifier oid : extensionControls.keySet()) {
        if (extensionControls.get(oid).isRequired()) {
            types.add(oid);//from  w  ww . ja  v  a2 s . c  o  m
        }
    }

    Set<ASN1ObjectIdentifier> wantedExtensionTypes = new HashSet<>();

    if (requestedExtensions != null) {
        Extension reqExtension = requestedExtensions
                .getExtension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions);
        if (reqExtension != null) {
            ExtensionExistence ee = ExtensionExistence.getInstance(reqExtension.getParsedValue());
            types.addAll(ee.getNeedExtensions());
            wantedExtensionTypes.addAll(ee.getWantExtensions());
        }
    }

    if (CollectionUtil.isEmpty(wantedExtensionTypes)) {
        return types;
    }

    // wanted extension types
    // Authority key identifier
    ASN1ObjectIdentifier type = Extension.authorityKeyIdentifier;
    if (wantedExtensionTypes.contains(type)) {
        types.add(type);
    }

    // Subject key identifier
    type = Extension.subjectKeyIdentifier;
    if (wantedExtensionTypes.contains(type)) {
        types.add(type);
    }

    // KeyUsage
    type = Extension.keyUsage;
    if (wantedExtensionTypes.contains(type)) {
        boolean required = false;
        if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) {
            required = true;
        }

        if (!required) {
            Set<KeyUsageControl> requiredKeyusage = getKeyusage(true);
            if (CollectionUtil.isNonEmpty(requiredKeyusage)) {
                required = true;
            }
        }

        if (required) {
            types.add(type);
        }
    }

    // CertificatePolicies
    type = Extension.certificatePolicies;
    if (wantedExtensionTypes.contains(type)) {
        if (certificatePolicies != null) {
            types.add(type);
        }
    }

    // Policy Mappings
    type = Extension.policyMappings;
    if (wantedExtensionTypes.contains(type)) {
        if (policyMappings != null) {
            types.add(type);
        }
    }

    // SubjectAltNames
    type = Extension.subjectAlternativeName;
    if (wantedExtensionTypes.contains(type)) {
        if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) {
            types.add(type);
        }
    }

    // IssuerAltName
    type = Extension.issuerAlternativeName;
    if (wantedExtensionTypes.contains(type)) {
        if (cert.getTBSCertificate().getExtensions().getExtension(Extension.subjectAlternativeName) != null) {
            types.add(type);
        }
    }

    // BasicConstraints
    type = Extension.basicConstraints;
    if (wantedExtensionTypes.contains(type)) {
        types.add(type);
    }

    // Name Constraints
    type = Extension.nameConstraints;
    if (wantedExtensionTypes.contains(type)) {
        if (nameConstraints != null) {
            types.add(type);
        }
    }

    // PolicyConstrains
    type = Extension.policyConstraints;
    if (wantedExtensionTypes.contains(type)) {
        if (policyConstraints != null) {
            types.add(type);
        }
    }

    // ExtendedKeyUsage
    type = Extension.extendedKeyUsage;
    if (wantedExtensionTypes.contains(type)) {
        boolean required = false;
        if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) {
            required = true;
        }

        if (!required) {
            Set<ExtKeyUsageControl> requiredExtKeyusage = getExtKeyusage(true);
            if (CollectionUtil.isNonEmpty(requiredExtKeyusage)) {
                required = true;
            }
        }

        if (required) {
            types.add(type);
        }
    }

    // CRLDistributionPoints
    type = Extension.cRLDistributionPoints;
    if (wantedExtensionTypes.contains(type)) {
        if (issuerInfo.getCrlUrls() != null) {
            types.add(type);
        }
    }

    // Inhibit anyPolicy
    type = Extension.inhibitAnyPolicy;
    if (wantedExtensionTypes.contains(type)) {
        if (inhibitAnyPolicy != null) {
            types.add(type);
        }
    }

    // FreshestCRL
    type = Extension.freshestCRL;
    if (wantedExtensionTypes.contains(type)) {
        if (issuerInfo.getDeltaCrlUrls() != null) {
            types.add(type);
        }
    }

    // AuthorityInfoAccess
    type = Extension.authorityInfoAccess;
    if (wantedExtensionTypes.contains(type)) {
        if (issuerInfo.getOcspUrls() != null) {
            types.add(type);
        }
    }

    // SubjectInfoAccess
    type = Extension.subjectInfoAccess;
    if (wantedExtensionTypes.contains(type)) {
        if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) {
            types.add(type);
        }
    }

    // Admission
    type = ObjectIdentifiers.id_extension_admission;
    if (wantedExtensionTypes.contains(type)) {
        if (certProfile.getAdmission() != null) {
            types.add(type);
        }
    }

    // ocsp-nocheck
    type = ObjectIdentifiers.id_extension_pkix_ocsp_nocheck;
    if (wantedExtensionTypes.contains(type)) {
        types.add(type);
    }

    wantedExtensionTypes.removeAll(types);

    for (ASN1ObjectIdentifier oid : wantedExtensionTypes) {
        if (requestedExtensions != null && requestedExtensions.getExtension(oid) != null) {
            if (constantExtensions.containsKey(oid)) {
                types.add(oid);
            }
        }
    }

    return types;
}

From source file:org.xipki.pki.ca.qa.X509CertprofileQa.java

License:Open Source License

public ValidationResult checkCert(final byte[] certBytes, final X509IssuerInfo issuerInfo,
        final X500Name requestedSubject, final SubjectPublicKeyInfo requestedPublicKey,
        final Extensions requestedExtensions) {
    ParamUtil.requireNonNull("certBytes", certBytes);
    ParamUtil.requireNonNull("issuerInfo", issuerInfo);
    ParamUtil.requireNonNull("requestedSubject", requestedSubject);
    ParamUtil.requireNonNull("requestedPublicKey", requestedPublicKey);

    List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>();

    Certificate bcCert;
    TBSCertificate tbsCert;//from w ww.  jav  a  2 s. co m
    X509Certificate cert;
    ValidationIssue issue;

    // certificate size
    issue = new ValidationIssue("X509.SIZE", "certificate size");
    resultIssues.add(issue);

    Integer maxSize = certProfile.getMaxSize();
    if (maxSize != 0) {
        int size = certBytes.length;
        if (size > maxSize) {
            issue.setFailureMessage(
                    String.format("certificate exceeds the maximal allowed size: %d > %d", size, maxSize));
        }
    }

    // certificate encoding
    issue = new ValidationIssue("X509.ENCODING", "certificate encoding");
    resultIssues.add(issue);
    try {
        bcCert = Certificate.getInstance(certBytes);
        tbsCert = bcCert.getTBSCertificate();
        cert = X509Util.parseCert(certBytes);
    } catch (CertificateException ex) {
        issue.setFailureMessage("certificate is not corrected encoded");
        return new ValidationResult(resultIssues);
    }

    // syntax version
    issue = new ValidationIssue("X509.VERSION", "certificate version");
    resultIssues.add(issue);
    int versionNumber = tbsCert.getVersionNumber();

    X509CertVersion expVersion = certProfile.getVersion();
    if (versionNumber != expVersion.getVersionNumber()) {
        issue.setFailureMessage(
                "is '" + versionNumber + "' but expected '" + expVersion.getVersionNumber() + "'");
    }

    // serialNumber
    issue = new ValidationIssue("X509.serialNumber", "certificate serial number");
    resultIssues.add(issue);
    BigInteger serialNumber = tbsCert.getSerialNumber().getValue();
    if (serialNumber.signum() != 1) {
        issue.setFailureMessage("not positive");
    } else {
        if (serialNumber.bitLength() >= 160) {
            issue.setFailureMessage("serial number has more than 20 octets");
        }
    }

    // signatureAlgorithm
    List<String> signatureAlgorithms = certProfile.getSignatureAlgorithms();
    if (CollectionUtil.isNonEmpty(signatureAlgorithms)) {
        issue = new ValidationIssue("X509.SIGALG", "signature algorithm");
        resultIssues.add(issue);

        AlgorithmIdentifier sigAlgId = bcCert.getSignatureAlgorithm();
        AlgorithmIdentifier tbsSigAlgId = tbsCert.getSignature();
        if (!tbsSigAlgId.equals(sigAlgId)) {
            issue.setFailureMessage("Certificate.tbsCertificate.signature != Certificate.signatureAlgorithm");
        }

        try {

            String sigAlgo = AlgorithmUtil.getSignatureAlgoName(sigAlgId);
            if (!issue.isFailed()) {
                if (!signatureAlgorithms.contains(sigAlgo)) {
                    issue.setFailureMessage("signatureAlgorithm '" + sigAlgo + "' is not allowed");
                }
            }

            // check parameters
            if (!issue.isFailed()) {
                AlgorithmIdentifier expSigAlgId = AlgorithmUtil.getSigAlgId(sigAlgo);
                if (!expSigAlgId.equals(sigAlgId)) {
                    issue.setFailureMessage("invalid parameters");
                }
            }
        } catch (NoSuchAlgorithmException ex) {
            issue.setFailureMessage("unsupported signature algorithm " + sigAlgId.getAlgorithm().getId());
        }
    }

    // notBefore encoding
    issue = new ValidationIssue("X509.NOTBEFORE.ENCODING", "notBefore encoding");
    checkTime(tbsCert.getStartDate(), issue);

    // notAfter encoding
    issue = new ValidationIssue("X509.NOTAFTER.ENCODING", "notAfter encoding");
    checkTime(tbsCert.getStartDate(), issue);

    // notBefore
    if (certProfile.isNotBeforeMidnight()) {
        issue = new ValidationIssue("X509.NOTBEFORE", "notBefore midnight");
        resultIssues.add(issue);
        Calendar cal = Calendar.getInstance(UTC);
        cal.setTime(cert.getNotBefore());
        int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);

        if (hourOfDay != 0 || minute != 0 || second != 0) {
            issue.setFailureMessage(" '" + cert.getNotBefore() + "' is not midnight time (UTC)");
        }
    }

    // validity
    issue = new ValidationIssue("X509.VALIDITY", "cert validity");
    resultIssues.add(issue);

    if (cert.getNotAfter().before(cert.getNotBefore())) {
        issue.setFailureMessage("notAfter must not be before notBefore");
    } else if (cert.getNotBefore().before(issuerInfo.getCaNotBefore())) {
        issue.setFailureMessage("notBefore must not be before CA's notBefore");
    } else {
        CertValidity validity = certProfile.getValidity();
        Date expectedNotAfter = validity.add(cert.getNotBefore());
        if (expectedNotAfter.getTime() > MAX_CERT_TIME_MS) {
            expectedNotAfter = new Date(MAX_CERT_TIME_MS);
        }

        if (issuerInfo.isCutoffNotAfter() && expectedNotAfter.after(issuerInfo.getCaNotAfter())) {
            expectedNotAfter = issuerInfo.getCaNotAfter();
        }

        if (Math.abs(expectedNotAfter.getTime() - cert.getNotAfter().getTime()) > 60 * SECOND) {
            issue.setFailureMessage("cert validity is not within " + validity.toString());
        }
    }

    // subjectPublicKeyInfo
    resultIssues.addAll(publicKeyChecker.checkPublicKey(bcCert.getSubjectPublicKeyInfo(), requestedPublicKey));

    // Signature
    issue = new ValidationIssue("X509.SIG", "whether certificate is signed by CA");
    resultIssues.add(issue);
    try {
        cert.verify(issuerInfo.getCert().getPublicKey(), "BC");
    } catch (Exception ex) {
        issue.setFailureMessage("invalid signature");
    }

    // issuer
    issue = new ValidationIssue("X509.ISSUER", "certificate issuer");
    resultIssues.add(issue);
    if (!cert.getIssuerX500Principal().equals(issuerInfo.getCert().getSubjectX500Principal())) {
        issue.setFailureMessage("issue in certificate does not equal the subject of CA certificate");
    }

    // subject
    resultIssues.addAll(subjectChecker.checkSubject(bcCert.getSubject(), requestedSubject));

    // issuerUniqueID
    issue = new ValidationIssue("X509.IssuerUniqueID", "issuerUniqueID");
    resultIssues.add(issue);
    if (tbsCert.getIssuerUniqueId() != null) {
        issue.setFailureMessage("is present but not permitted");
    }

    // subjectUniqueID
    issue = new ValidationIssue("X509.SubjectUniqueID", "subjectUniqueID");
    resultIssues.add(issue);
    if (tbsCert.getSubjectUniqueId() != null) {
        issue.setFailureMessage("is present but not permitted");
    }

    // extensions
    issue = new ValidationIssue("X509.GrantedSubject", "grantedSubject");
    resultIssues.add(issue);

    resultIssues.addAll(
            extensionsChecker.checkExtensions(bcCert, issuerInfo, requestedExtensions, requestedSubject));

    return new ValidationResult(resultIssues);
}