Search in sources :

Example 1 with CrlID

use of org.bouncycastle.asn1.ocsp.CrlID in project robovm by robovm.

the class CRLBag method toASN1Primitive.

/**
     * <pre>
     CRLBag ::= SEQUENCE {
     crlId  BAG-TYPE.&id ({CRLTypes}),
     crlValue  [0] EXPLICIT BAG-TYPE.&Type ({CRLTypes}{@crlId})
     }

     x509CRL BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}
     -- DER-encoded X.509 CRL stored in OCTET STRING

     CRLTypes BAG-TYPE ::= {
     x509CRL,
     ... -- For future extensions
     }
       </pre>
     */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(crlId);
    v.add(new DERTaggedObject(0, crlValue));
    return new DERSequence(v);
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector)

Example 2 with CrlID

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

the class ImportCrl method importCa.

private int importCa(Connection conn) throws DataAccessException, ImportCrlException {
    byte[] encodedCaCert;
    try {
        encodedCaCert = caCert.getEncoded();
    } catch (CertificateEncodingException ex) {
        throw new ImportCrlException("could not encode CA certificate");
    }
    String fpCaCert = HashAlgo.SHA1.base64Hash(encodedCaCert);
    Integer issuerId = null;
    CrlInfo crlInfo = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = null;
    try {
        sql = "SELECT ID,CRL_INFO FROM ISSUER WHERE S1C=?";
        ps = datasource.prepareStatement(conn, sql);
        ps.setString(1, fpCaCert);
        rs = ps.executeQuery();
        if (rs.next()) {
            issuerId = rs.getInt("ID");
            String str = rs.getString("CRL_INFO");
            if (str == null) {
                throw new ImportCrlException("RequestIssuer for the given CA of CRL exists, but not imported from CRL");
            }
            crlInfo = new CrlInfo(str);
        }
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseResources(ps, rs);
    }
    boolean addNew = (issuerId == null);
    if (addNew) {
        if (isDeltaCrl) {
            throw new ImportCrlException("Given CRL is a deltaCRL for the full CRL with number " + baseCrlNumber + ", please import this full CRL first.");
        } else {
            crlInfo = new CrlInfo(crlNumber, null, useCrlUpdates, crl.getThisUpdate(), crl.getNextUpdate(), crlId);
        }
    } else {
        if (crlNumber.compareTo(crlInfo.getCrlNumber()) < 0) {
            // which enables the resume of importing process if error occurred.
            throw new ImportCrlException("Given CRL is not newer than existing CRL.");
        }
        if (isDeltaCrl) {
            BigInteger lastFullCrlNumber = crlInfo.getBaseCrlNumber();
            if (lastFullCrlNumber == null) {
                lastFullCrlNumber = crlInfo.getCrlNumber();
            }
            if (!baseCrlNumber.equals(lastFullCrlNumber)) {
                throw new ImportCrlException("Given CRL is a deltaCRL for the full CRL with number " + crlNumber + ", please import this full CRL first.");
            }
        }
        crlInfo.setCrlNumber(crlNumber);
        crlInfo.setBaseCrlNumber(isDeltaCrl ? baseCrlNumber : null);
        crlInfo.setThisUpdate(crl.getThisUpdate());
        crlInfo.setNextUpdate(crl.getNextUpdate());
    }
    ps = null;
    rs = null;
    sql = null;
    try {
        // issuer exists
        if (addNew) {
            int maxId = (int) datasource.getMax(conn, "ISSUER", "ID");
            issuerId = maxId + 1;
            sql = "INSERT INTO ISSUER (ID,SUBJECT,NBEFORE,NAFTER,S1C,CERT,REV,RT,RIT,CRL_INFO)" + " VALUES(?,?,?,?,?,?,?,?,?,?)";
        } else {
            sql = "UPDATE ISSUER SET REV=?,RT=?,RIT=?,CRL_INFO=? WHERE ID=?";
        }
        ps = datasource.prepareStatement(conn, sql);
        int offset = 1;
        if (addNew) {
            String subject = X509Util.getRfc4519Name(caCert.getSubjectX500Principal());
            ps.setInt(offset++, issuerId);
            ps.setString(offset++, subject);
            ps.setLong(offset++, caCert.getNotBefore().getTime() / 1000);
            ps.setLong(offset++, caCert.getNotAfter().getTime() / 1000);
            ps.setString(offset++, fpCaCert);
            ps.setString(offset++, Base64.encodeToString(encodedCaCert));
        }
        ps.setInt(offset++, (caRevInfo == null) ? 0 : 1);
        Date revTime = null;
        Date revInvTime = null;
        if (caRevInfo != null) {
            revTime = caRevInfo.getRevocationTime();
            revInvTime = caRevInfo.getInvalidityTime();
        }
        if (revTime != null) {
            ps.setLong(offset++, revTime.getTime() / 1000);
        } else {
            ps.setNull(offset++, Types.BIGINT);
        }
        if (revInvTime != null) {
            ps.setLong(offset++, revInvTime.getTime() / 1000);
        } else {
            ps.setNull(offset++, Types.BIGINT);
        }
        // CRL info
        try {
            ps.setString(offset++, crlInfo.getEncoded());
        } catch (IOException ex) {
            throw new ImportCrlException("could not encode the Crlinfo", ex);
        }
        if (!addNew) {
            ps.setInt(offset++, issuerId.intValue());
        }
        ps.executeUpdate();
        return issuerId.intValue();
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseResources(ps, rs);
    }
}
Also used : SQLException(java.sql.SQLException) CertificateEncodingException(java.security.cert.CertificateEncodingException) PreparedStatement(java.sql.PreparedStatement) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) IOException(java.io.IOException) Date(java.util.Date) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) BigInteger(java.math.BigInteger) CrlInfo(org.xipki.ocsp.api.CrlInfo) ResultSet(java.sql.ResultSet) BigInteger(java.math.BigInteger)

Example 3 with CrlID

use of org.bouncycastle.asn1.ocsp.CrlID in project signer by demoiselle.

the class RevocationRefs method makeCrlValidatedID.

/**
 * @param crl CrlValidatedID from X509CRL
 * @return a CrlValidatedID
 * @throws NoSuchAlgorithmException
 * @throws CRLException
 */
private CrlValidatedID makeCrlValidatedID(X509CRL crl) throws CRLException {
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
    OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256), new DEROctetString(digest.digest(crl.getEncoded())));
    OtherHash hash = new OtherHash(otherHashAlgAndValue);
    BigInteger crlnumber;
    CrlIdentifier crlid;
    if (crl.getExtensionValue("2.5.29.20") != null) {
        ASN1Integer varASN1Integer = new ASN1Integer(crl.getExtensionValue("2.5.29.20"));
        crlnumber = varASN1Integer.getPositiveValue();
        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()), new DERUTCTime(crl.getThisUpdate()), crlnumber);
    } else {
        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()), new DERUTCTime(crl.getThisUpdate()));
    }
    CrlValidatedID crlvid = new CrlValidatedID(hash, crlid);
    return crlvid;
}
Also used : CrlValidatedID(org.bouncycastle.asn1.esf.CrlValidatedID) Digest(org.demoiselle.signer.cryptography.Digest) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) BigInteger(java.math.BigInteger) CrlIdentifier(org.bouncycastle.asn1.esf.CrlIdentifier) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) X500Name(org.bouncycastle.asn1.x500.X500Name) OtherHashAlgAndValue(org.bouncycastle.asn1.esf.OtherHashAlgAndValue) DEROctetString(org.bouncycastle.asn1.DEROctetString) OtherHash(org.bouncycastle.asn1.esf.OtherHash) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 4 with CrlID

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

the class ImportCrl method importCrl.

// method importCrlToOcspDb
private void importCrl(Connection conn, CrlDirInfo crlDirInfo) {
    File crlDir = crlDirInfo.crlDir;
    File generatedDir = new File(crlDir, ".generated");
    generatedDir.mkdirs();
    // Delete the files UPDATE.SUCC and UPDATE.FAIL
    IoUtil.deleteFile(new File(generatedDir, "UPDATEME.SUCC"));
    IoUtil.deleteFile(new File(generatedDir, "UPDATEME.FAIL"));
    long startTimeSec = System.currentTimeMillis() / 1000;
    int id = crlDirInfo.crlId;
    String crlName = crlDirInfo.crlName;
    boolean updateSucc = false;
    CertWrapper caCert = null;
    try {
        LOG.info("Importing CRL (id={}, name={}) in the folder {}", id, crlName, crlDir.getPath());
        File caCertFile = new File(crlDir, "ca.crt");
        try {
            X509Cert cert = X509Util.parseCert(caCertFile);
            caCert = new CertWrapper(cert);
        } catch (CertificateException ex) {
            LOG.error("could not parse CA certificate " + caCertFile.getPath(), ex);
            return;
        }
        CrlStreamParser crl = null;
        CrlInfo crlInfo = null;
        if (!crlDirInfo.deleteMe && crlDirInfo.revocationinfo == null) {
            crl = new CrlStreamParser(crlDirInfo.crlFile);
            Date now = new Date();
            if (crl.getNextUpdate() != null && crl.getNextUpdate().before(now)) {
                if (ignoreExpiredCrls) {
                    LOG.error("CRL is expired, ignore it");
                    return;
                }
            } else if (crl.getThisUpdate().after(now)) {
                LOG.error("CRL is not valid yet, ignore it");
                return;
            }
            X500Name issuer = crl.getIssuer();
            X509Cert crlSignerCert;
            if (caCert.subject.equals(issuer)) {
                crlSignerCert = caCert.cert;
            } else {
                X509Cert crlIssuerCert = null;
                File issuerCertFile = new File(crlDir, "issuer.crt");
                if (issuerCertFile.exists()) {
                    crlIssuerCert = parseCert(issuerCertFile);
                }
                if (crlIssuerCert == null) {
                    LOG.error("issuerCert may not be null");
                    return;
                }
                if (!crlIssuerCert.getSubject().equals(issuer)) {
                    LOG.error("issuerCert and CRL do not match");
                    return;
                }
                crlSignerCert = crlIssuerCert;
            }
            if (crl.getCrlNumber() == null) {
                LOG.error("crlNumber is not specified, ignore the CRL");
                return;
            }
            LOG.info("The CRL is a {}", crl.isDeltaCrl() ? "DeltaCRL" : "FullCRL");
            File urlFile = new File(basedir, "crl.url");
            // Construct CrlID
            ASN1EncodableVector vec = new ASN1EncodableVector();
            if (crlDirInfo.crlDownloded) {
                File crlDownloadFile = new File(basedir, "crl.download");
                Properties props = CrlDbCertStatusStore.loadProperties(crlDownloadFile);
                String crldp = props.getProperty("crldp");
                if (StringUtil.isNotBlank(crldp)) {
                    vec.add(new DERTaggedObject(true, 0, new DERIA5String(crldp, true)));
                }
                if (urlFile.exists()) {
                    LOG.warn("use {} only, ignore {}", crlDownloadFile.getPath(), urlFile.getPath());
                }
            } else {
                if (urlFile.exists()) {
                    String crlUrl = StringUtil.toUtf8String(IoUtil.read(urlFile)).trim();
                    if (StringUtil.isNotBlank(crlUrl)) {
                        vec.add(new DERTaggedObject(true, 0, new DERIA5String(crlUrl, true)));
                    }
                }
            }
            vec.add(new DERTaggedObject(true, 1, new ASN1Integer(crl.getCrlNumber())));
            vec.add(new DERTaggedObject(true, 2, new ASN1GeneralizedTime(crl.getThisUpdate())));
            CrlID crlId = CrlID.getInstance(new DERSequence(vec));
            BigInteger crlNumber = crl.getCrlNumber();
            BigInteger baseCrlNumber = crl.getBaseCrlNumber();
            String str = datasource.getFirstStringValue(conn, "CRL_INFO", "INFO", "ID='" + id + "'");
            boolean addNew = str == null;
            if (addNew) {
                if (crl.isDeltaCrl()) {
                    LOG.error("Given CRL is a DeltaCRL for the full CRL with number {}, " + "please import this full CRL first.", baseCrlNumber);
                    return;
                }
            } else {
                CrlInfo oldCrlInfo = new CrlInfo(str);
                if (crlNumber.compareTo(oldCrlInfo.getCrlNumber()) < 0) {
                    // It is permitted if the CRL number equals to the one in Database.
                    // This enables the resume of importing process if error occurred.
                    LOG.error("Given CRL is older than existing CRL, ignore it");
                    return;
                }
                if (crl.isDeltaCrl()) {
                    BigInteger lastFullCrlNumber = oldCrlInfo.getBaseCrlNumber();
                    if (lastFullCrlNumber == null) {
                        lastFullCrlNumber = oldCrlInfo.getCrlNumber();
                    }
                    if (!baseCrlNumber.equals(lastFullCrlNumber)) {
                        LOG.error("Given CRL is a deltaCRL for the full CRL with number {}, " + "please import this full CRL first.", crlNumber);
                        return;
                    }
                }
            }
            // Verify the signature
            if (!crl.verifySignature(crlSignerCert.getSubjectPublicKeyInfo())) {
                LOG.error("signature of CRL is invalid, ignore the CRL");
                return;
            }
            crlInfo = new CrlInfo(crlNumber, baseCrlNumber, crl.getThisUpdate(), crl.getNextUpdate(), crlId);
        }
        if (crlDirInfo.deleteMe) {
            deleteCa(conn, crlDirInfo, caCert);
        } else {
            importCa(conn, crlDirInfo, caCert);
        }
        commit(conn);
        if (crl == null) {
            LOG.info("Ignored CRL (name={}) in the folder {}: CA is revoked", crlName, crlDir.getPath());
        } else {
            importCrlInfo(conn, id, crlName, crlInfo, crlDirInfo.shareCaWithOtherCrl, caCert.base64Sha1Fp);
            commit(conn);
            importCrlRevokedCertificates(conn, id, caCert, crl, crlDir, startTimeSec);
            commit(conn);
            if (!crl.isDeltaCrl()) {
                deleteEntriesNotUpdatedSince(conn, id, startTimeSec);
                commit(conn);
            }
        }
        if (crlDirInfo.crlDownloded) {
            crlDirInfo.crlFile.renameTo(new File(generatedDir, "ca.crl"));
            File newCrlFpFile = new File(generatedDir, "new-ca.crl.fp");
            String hashInfo = new String(IoUtil.read(newCrlFpFile));
            String info = "crlnumber=" + crlInfo.getCrlNumber().toString() + "\nnextupdate=" + DateUtil.toUtcTimeyyyyMMddhhmmss(crlInfo.getNextUpdate()) + "\nhash=" + hashInfo;
            IoUtil.save(new File(generatedDir, "ca.crl.info"), info.getBytes(StandardCharsets.UTF_8));
            newCrlFpFile.delete();
        }
        updateSucc = true;
        LOG.info("Imported CRL (id={}) in the folder {}", id, crlDir.getPath());
    } catch (Throwable th) {
        LOG.error(String.format("Importing CRL (id=%s) in the folder %s FAILED", id, crlDir.getPath()), th);
    } finally {
        try {
            commit(conn);
        } catch (Throwable th) {
            LOG.error(String.format("Importing CRL (id=%s) in the folder %s FAILED (Connect.commit)", id, crlDir.getPath()), th);
        }
        crlDirInfo.updatemeFile.setLastModified(System.currentTimeMillis());
        crlDirInfo.updatemeFile.renameTo(new File(generatedDir, "UPDATEME." + (updateSucc ? "SUCC" : "FAIL")));
        if (!updateSucc && caCert != null) {
            if (!crlDirInfo.shareCaWithOtherCrl && caCert.databaseId != null) {
                // try to delete the issuer if no certificate is associated with it
                try {
                    datasource.deleteFromTableWithException(conn, "ISSUER", "ID", caCert.databaseId);
                } catch (Throwable th) {
                    LOG.warn("error deleting from table ISSUER for ID {}", caCert.databaseId);
                }
            }
        }
        if (!updateSucc && crlDirInfo.crlDownloded & crlDirInfo.crlFile.exists()) {
            crlDirInfo.crlFile.renameTo(new File(generatedDir, "INVALID-new-ca.crl"));
        }
    }
}
Also used : CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) CrlStreamParser(org.xipki.security.asn1.CrlStreamParser) X509Cert(org.xipki.security.X509Cert) BigInteger(java.math.BigInteger) File(java.io.File) CrlID(org.bouncycastle.asn1.ocsp.CrlID)

Example 5 with CrlID

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

the class CertStoreQueryExecutor method addCrl.

void addCrl(NameId ca, X509CRL crl) throws DataAccessException, CRLException {
    ParamUtil.requireNonNull("ca", ca);
    ParamUtil.requireNonNull("crl", crl);
    byte[] encodedExtnValue = crl.getExtensionValue(Extension.cRLNumber.getId());
    Long crlNumber = null;
    if (encodedExtnValue != null) {
        byte[] extnValue = DEROctetString.getInstance(encodedExtnValue).getOctets();
        crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue().longValue();
    }
    encodedExtnValue = crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
    Long baseCrlNumber = null;
    if (encodedExtnValue != null) {
        byte[] extnValue = DEROctetString.getInstance(encodedExtnValue).getOctets();
        baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue().longValue();
    }
    final String sql = SQLs.SQL_ADD_CRL;
    long currentMaxCrlId = datasource.getMax(null, "CRL", "ID");
    long crlId = currentMaxCrlId + 1;
    String b64Crl = Base64.encodeToString(crl.getEncoded());
    PreparedStatement ps = null;
    try {
        ps = borrowPreparedStatement(sql);
        int idx = 1;
        ps.setLong(idx++, crlId);
        ps.setInt(idx++, ca.getId());
        setLong(ps, idx++, crlNumber);
        Date date = crl.getThisUpdate();
        ps.setLong(idx++, date.getTime() / 1000);
        setDateSeconds(ps, idx++, crl.getNextUpdate());
        setBoolean(ps, idx++, (baseCrlNumber != null));
        setLong(ps, idx++, baseCrlNumber);
        ps.setString(idx++, b64Crl);
        ps.executeUpdate();
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseDbResources(ps, null);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date)

Aggregations

BigInteger (java.math.BigInteger)3 Date (java.util.Date)3 DEROctetString (org.bouncycastle.asn1.DEROctetString)3 IOException (java.io.IOException)2 PreparedStatement (java.sql.PreparedStatement)2 SQLException (java.sql.SQLException)2 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)2 X500Name (org.bouncycastle.asn1.x500.X500Name)2 File (java.io.File)1 CRLException (java.security.cert.CRLException)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 CertificateException (java.security.cert.CertificateException)1 ResultSet (java.sql.ResultSet)1 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)1 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)1 DERIA5String (org.bouncycastle.asn1.DERIA5String)1 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)1 DERSequence (org.bouncycastle.asn1.DERSequence)1 DERTaggedObject (org.bouncycastle.asn1.DERTaggedObject)1 DERUTCTime (org.bouncycastle.asn1.DERUTCTime)1