use of org.bouncycastle.asn1.x509.CRLNumber 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);
}
}
use of org.bouncycastle.asn1.x509.CRLNumber in project xipki by xipki.
the class CertStoreQueryExecutor method cleanupCrls.
// method getEncodedCrl
int cleanupCrls(NameId ca, int numCrls) throws DataAccessException {
ParamUtil.requireNonNull("ca", ca);
ParamUtil.requireMin("numCrls", numCrls, 1);
String sql = "SELECT CRL_NO FROM CRL WHERE CA_ID=? AND DELTACRL=?";
PreparedStatement ps = borrowPreparedStatement(sql);
List<Integer> crlNumbers = new LinkedList<>();
ResultSet rs = null;
try {
ps.setInt(1, ca.getId());
setBoolean(ps, 2, false);
rs = ps.executeQuery();
while (rs.next()) {
int crlNumber = rs.getInt("CRL_NO");
crlNumbers.add(crlNumber);
}
} catch (SQLException ex) {
throw datasource.translate(sql, ex);
} finally {
releaseDbResources(ps, rs);
}
int size = crlNumbers.size();
Collections.sort(crlNumbers);
int numCrlsToDelete = size - numCrls;
if (numCrlsToDelete < 1) {
return 0;
}
int crlNumber = crlNumbers.get(numCrlsToDelete - 1);
sql = "DELETE FROM CRL WHERE CA_ID=? AND CRL_NO<?";
ps = borrowPreparedStatement(sql);
try {
int idx = 1;
ps.setInt(idx++, ca.getId());
ps.setInt(idx++, crlNumber + 1);
ps.executeUpdate();
} catch (SQLException ex) {
throw datasource.translate(sql, ex);
} finally {
releaseDbResources(ps, null);
}
return numCrlsToDelete;
}
use of org.bouncycastle.asn1.x509.CRLNumber in project xipki by xipki.
the class CaCertStoreDbExporter method exportEntries.
private void exportEntries(CaDbEntryType type, CertStoreType certstore, File processLogFile, FileOutputStream filenameListOs, Long idProcessedInLastProcess) throws Exception {
final int numEntriesPerSelect = Math.max(1, Math.round(type.getSqlBatchFactor() * numCertsPerSelect));
final int numEntriesPerZip = Math.max(1, Math.round(type.getSqlBatchFactor() * numCertsInBundle));
final File entriesDir = new File(baseDir, type.getDirName());
final String tableName = type.getTableName();
int numProcessedBefore;
String coreSql;
switch(type) {
case CERT:
numProcessedBefore = certstore.getCountCerts();
coreSql = "ID,SN,CA_ID,PID,RID,ART,RTYPE,TID,UID,EE,LUPDATE,REV,RR,RT,RIT,FP_RS," + "REQ_SUBJECT,CERT FROM CERT INNER JOIN CRAW ON CERT.ID>=? AND CERT.ID=CRAW.CID";
break;
case CRL:
numProcessedBefore = certstore.getCountCrls();
coreSql = "ID,CA_ID,CRL FROM CRL WHERE ID>=?";
break;
case REQUEST:
numProcessedBefore = certstore.getCountRequests();
coreSql = "ID,LUPDATE,DATA FROM REQUEST WHERE ID>=?";
break;
case REQCERT:
numProcessedBefore = certstore.getCountReqCerts();
coreSql = "ID,RID,CID FROM REQCERT WHERE ID>=?";
break;
default:
throw new RuntimeException("unknown CaDbEntryType " + type);
}
Long minId = (idProcessedInLastProcess != null) ? idProcessedInLastProcess + 1 : min(tableName, "ID");
String tablesText = (CaDbEntryType.CERT == type) ? "tables " + tableName + " and CRAW" : "table " + type.getTableName();
System.out.println(exportingText() + tablesText + " from ID " + minId);
final long maxId = max(tableName, "ID");
long total = count(tableName) - numProcessedBefore;
if (total < 1) {
// to avoid exception
total = 1;
}
String sql = datasource.buildSelectFirstSql(numEntriesPerSelect, "ID ASC", coreSql);
DbiXmlWriter entriesInCurrentFile = createWriter(type);
PreparedStatement ps = prepareStatement(sql.toString());
int numEntriesInCurrentFile = 0;
int sum = 0;
File currentEntriesZipFile = new File(baseDir, "tmp-" + type.getDirName() + "-" + System.currentTimeMillis() + ".zip");
ZipOutputStream currentEntriesZip = getZipOutputStream(currentEntriesZipFile);
long minIdOfCurrentFile = -1;
long maxIdOfCurrentFile = -1;
ProcessLog processLog = new ProcessLog(total);
processLog.printHeader();
try {
Long id = null;
boolean interrupted = false;
long lastMaxId = minId - 1;
while (true) {
if (stopMe.get()) {
interrupted = true;
break;
}
ps.setLong(1, lastMaxId + 1);
ResultSet rs = ps.executeQuery();
// no entries anymore
if (!rs.next()) {
break;
}
do {
id = rs.getLong("ID");
if (lastMaxId < id) {
lastMaxId = id;
}
if (minIdOfCurrentFile == -1) {
minIdOfCurrentFile = id;
} else if (minIdOfCurrentFile > id) {
minIdOfCurrentFile = id;
}
if (maxIdOfCurrentFile == -1) {
maxIdOfCurrentFile = id;
} else if (maxIdOfCurrentFile < id) {
maxIdOfCurrentFile = id;
}
if (CaDbEntryType.CERT == type) {
String b64Cert = rs.getString("CERT");
byte[] certBytes = Base64.decodeFast(b64Cert);
String sha1 = HashAlgo.SHA1.hexHash(certBytes);
String certFileName = sha1 + ".der";
if (!evaulateOnly) {
ZipEntry certZipEntry = new ZipEntry(certFileName);
currentEntriesZip.putNextEntry(certZipEntry);
try {
currentEntriesZip.write(certBytes);
} finally {
currentEntriesZip.closeEntry();
}
}
CertType cert = new CertType();
cert.setId(id);
cert.setArt(rs.getInt("ART"));
cert.setCaId(rs.getInt("CA_ID"));
cert.setEe(rs.getBoolean("EE"));
cert.setFile(certFileName);
long fpReqSubject = rs.getLong("FP_RS");
if (fpReqSubject != 0) {
cert.setFpRs(fpReqSubject);
cert.setRs(rs.getString("REQ_SUBJECT"));
}
cert.setPid(rs.getInt("PID"));
cert.setReqType(rs.getInt("RTYPE"));
cert.setRid(rs.getInt("RID"));
cert.setSn(rs.getString("SN"));
String str = rs.getString("TID");
if (StringUtil.isNotBlank(str)) {
cert.setTid(str);
}
int userId = rs.getInt("UID");
if (userId != 0) {
cert.setUid(userId);
}
cert.setUpdate(rs.getLong("LUPDATE"));
boolean revoked = rs.getBoolean("REV");
cert.setRev(revoked);
if (revoked) {
cert.setRr(rs.getInt("RR"));
cert.setRt(rs.getLong("RT"));
long revInvTime = rs.getLong("RIT");
if (revInvTime != 0) {
cert.setRit(revInvTime);
}
}
((CertsWriter) entriesInCurrentFile).add(cert);
} else if (CaDbEntryType.CRL == type) {
String b64Crl = rs.getString("CRL");
byte[] crlBytes = Base64.decodeFast(b64Crl);
X509CRL x509Crl = null;
try {
x509Crl = X509Util.parseCrl(crlBytes);
} catch (CRLException ex) {
LogUtil.error(LOG, ex, "could not parse CRL with id " + id);
throw ex;
} catch (Exception ex) {
LogUtil.error(LOG, ex, "could not parse CRL with id " + id);
throw new CRLException(ex.getMessage(), ex);
}
byte[] octetString = x509Crl.getExtensionValue(Extension.cRLNumber.getId());
if (octetString == null) {
LOG.warn("CRL without CRL number, ignore it");
continue;
}
String sha1 = HashAlgo.SHA1.hexHash(crlBytes);
final String crlFilename = sha1 + ".crl";
if (!evaulateOnly) {
ZipEntry certZipEntry = new ZipEntry(crlFilename);
currentEntriesZip.putNextEntry(certZipEntry);
try {
currentEntriesZip.write(crlBytes);
} finally {
currentEntriesZip.closeEntry();
}
}
CrlType crl = new CrlType();
crl.setId(id);
crl.setCaId(rs.getInt("CA_ID"));
byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
BigInteger crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
crl.setCrlNo(crlNumber.toString());
crl.setFile(crlFilename);
((CrlsWriter) entriesInCurrentFile).add(crl);
} else if (CaDbEntryType.REQUEST == type) {
long update = rs.getLong("LUPDATE");
String b64Data = rs.getString("DATA");
byte[] dataBytes = Base64.decodeFast(b64Data);
String sha1 = HashAlgo.SHA1.hexHash(dataBytes);
final String dataFilename = sha1 + ".req";
if (!evaulateOnly) {
ZipEntry certZipEntry = new ZipEntry(dataFilename);
currentEntriesZip.putNextEntry(certZipEntry);
try {
currentEntriesZip.write(dataBytes);
} finally {
currentEntriesZip.closeEntry();
}
}
RequestType entry = new RequestType();
entry.setId(id);
entry.setUpdate(update);
entry.setFile(dataFilename);
((RequestsWriter) entriesInCurrentFile).add(entry);
} else if (CaDbEntryType.REQCERT == type) {
long cid = rs.getLong("CID");
long rid = rs.getLong("RID");
RequestCertType entry = new RequestCertType();
entry.setId(id);
entry.setCid(cid);
entry.setRid(rid);
((RequestCertsWriter) entriesInCurrentFile).add(entry);
} else {
throw new RuntimeException("unknown CaDbEntryType " + type);
}
numEntriesInCurrentFile++;
sum++;
if (numEntriesInCurrentFile == numEntriesPerZip) {
String currentEntriesFilename = buildFilename(type.getDirName() + "_", ".zip", minIdOfCurrentFile, maxIdOfCurrentFile, maxId);
finalizeZip(currentEntriesZip, "overview.xml", entriesInCurrentFile);
currentEntriesZipFile.renameTo(new File(entriesDir, currentEntriesFilename));
writeLine(filenameListOs, currentEntriesFilename);
setCount(type, certstore, numProcessedBefore + sum);
echoToFile(tableName + ":" + Long.toString(id), processLogFile);
processLog.addNumProcessed(numEntriesInCurrentFile);
processLog.printStatus();
// reset
entriesInCurrentFile = createWriter(type);
numEntriesInCurrentFile = 0;
minIdOfCurrentFile = -1;
maxIdOfCurrentFile = -1;
currentEntriesZipFile = new File(baseDir, "tmp-" + type.getDirName() + "-" + System.currentTimeMillis() + ".zip");
currentEntriesZip = getZipOutputStream(currentEntriesZipFile);
}
} while (rs.next());
rs.close();
}
if (interrupted) {
currentEntriesZip.close();
throw new InterruptedException("interrupted by the user");
}
if (numEntriesInCurrentFile > 0) {
finalizeZip(currentEntriesZip, "overview.xml", entriesInCurrentFile);
String currentEntriesFilename = buildFilename(type.getDirName() + "_", ".zip", minIdOfCurrentFile, maxIdOfCurrentFile, maxId);
currentEntriesZipFile.renameTo(new File(entriesDir, currentEntriesFilename));
writeLine(filenameListOs, currentEntriesFilename);
setCount(type, certstore, numProcessedBefore + sum);
if (id != null) {
echoToFile(Long.toString(id), processLogFile);
}
processLog.addNumProcessed(numEntriesInCurrentFile);
} else {
currentEntriesZip.close();
currentEntriesZipFile.delete();
}
} catch (SQLException ex) {
throw translate(null, ex);
} finally {
releaseResources(ps, null);
}
// end try
processLog.printTrailer();
// all successful, delete the processLogFile
processLogFile.delete();
System.out.println(exportedText() + sum + " entries from " + tablesText);
}
use of org.bouncycastle.asn1.x509.CRLNumber in project certmgr by hdecarne.
the class X509CRLHelper method generateCRL.
/**
* Generate a CRL object.
*
* @param currentCRL The current CRL object in case of an update (may be {@code null}).
* @param lastUpdate The last update timestamp to set.
* @param nextUpdate The next update timestamp to set (may be {@code null}).
* @param revokeEntries The revoked entries.
* @param issuerDN The CRL issuer's DN.
* @param issuerKey The CRL issuer's key pair.
* @param signatureAlgorithm The signature algorithm to use for signing.
* @return The generated CRL object.
* @throws IOException if an error occurs during generation.
*/
public static X509CRL generateCRL(@Nullable X509CRL currentCRL, Date lastUpdate, @Nullable Date nextUpdate, Map<BigInteger, ReasonFlag> revokeEntries, X500Principal issuerDN, KeyPair issuerKey, SignatureAlgorithm signatureAlgorithm) throws IOException {
LOG.info("CRL generation ''{0}'' started...", issuerDN);
// Initialize CRL builder
JcaX509v2CRLBuilder crlBuilder = new JcaX509v2CRLBuilder(issuerDN, lastUpdate);
if (nextUpdate != null) {
crlBuilder.setNextUpdate(nextUpdate);
}
for (Map.Entry<BigInteger, ReasonFlag> revokeEntry : revokeEntries.entrySet()) {
crlBuilder.addCRLEntry(revokeEntry.getKey(), lastUpdate, revokeEntry.getValue().value());
}
X509CRL crl;
try {
// Add extensions
JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(issuerKey.getPublic()));
BigInteger nextCRLNumber = getNextCRLNumber(currentCRL);
crlBuilder.addExtension(Extension.cRLNumber, false, new CRLNumber(nextCRLNumber));
// Sign and create CRL object
ContentSigner crlSigner = new JcaContentSignerBuilder(signatureAlgorithm.algorithm()).build(issuerKey.getPrivate());
crl = new JcaX509CRLConverter().getCRL(crlBuilder.build(crlSigner));
} catch (GeneralSecurityException | OperatorCreationException e) {
throw new CertProviderException(e);
}
LOG.info("CRT generation ''{0}'' done", issuerDN);
return crl;
}
use of org.bouncycastle.asn1.x509.CRLNumber in project candlepin by candlepin.
the class X509CRLStreamWriter method updateExtensions.
/**
* This method updates the crlNumber and authorityKeyIdentifier extensions. Any
* other extensions are copied over unchanged.
* @param obj
* @return
* @throws IOException
*/
@SuppressWarnings("rawtypes")
protected byte[] updateExtensions(byte[] obj) throws IOException {
ASN1TaggedObject taggedExts = (ASN1TaggedObject) new ASN1InputStream(obj).readObject();
ASN1Sequence seq = (ASN1Sequence) taggedExts.getObject();
ASN1EncodableVector modifiedExts = new ASN1EncodableVector();
// Now we need to read the extensions and find the CRL number and increment it,
// and determine if its length changed.
Enumeration objs = seq.getObjects();
while (objs.hasMoreElements()) {
ASN1Sequence ext = (ASN1Sequence) objs.nextElement();
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) ext.getObjectAt(0);
if (Extension.cRLNumber.equals(oid)) {
ASN1OctetString s = (ASN1OctetString) ext.getObjectAt(1);
ASN1Integer i = (ASN1Integer) new ASN1InputStream(s.getOctets()).readObject();
ASN1Integer newCrlNumber = new ASN1Integer(i.getValue().add(BigInteger.ONE));
Extension newNumberExt = new Extension(Extension.cRLNumber, false, new DEROctetString(newCrlNumber.getEncoded()));
ASN1EncodableVector crlNumber = new ASN1EncodableVector();
crlNumber.add(Extension.cRLNumber);
crlNumber.add(newNumberExt.getExtnValue());
modifiedExts.add(new DERSequence(crlNumber));
} else if (Extension.authorityKeyIdentifier.equals(oid)) {
Extension newAuthorityKeyExt = new Extension(Extension.authorityKeyIdentifier, false, aki.getEncoded());
ASN1EncodableVector aki = new ASN1EncodableVector();
aki.add(Extension.authorityKeyIdentifier);
aki.add(newAuthorityKeyExt.getExtnValue());
modifiedExts.add(new DERSequence(aki));
} else {
modifiedExts.add(ext);
}
}
ASN1Sequence seqOut = new DERSequence(modifiedExts);
ASN1TaggedObject out = new DERTaggedObject(true, 0, seqOut);
return out.getEncoded();
}
Aggregations