List of usage examples for org.bouncycastle.asn1.x509 Certificate getInstance
public static Certificate getInstance(Object obj)
From source file:org.xipki.commons.security.shell.CertInfoCmd.java
License:Open Source License
@Override protected Object doExecute() throws Exception { Certificate cert = Certificate.getInstance(IoUtil.read(inFile)); if (serial != null && serial) { return getNumber(cert.getSerialNumber().getPositiveValue()); } else if (subject != null && subject) { return cert.getSubject().toString(); } else if (issuer != null && issuer) { return cert.getIssuer().toString(); } else if (notBefore != null && notBefore) { return toUtcTimeyyyyMMddhhmmssZ(cert.getStartDate().getDate()); } else if (notAfter != null && notAfter) { return toUtcTimeyyyyMMddhhmmssZ(cert.getEndDate().getDate()); } else if (fingerprint != null && fingerprint) { byte[] encoded = cert.getEncoded(); return HashAlgoType.getHashAlgoType(hashAlgo).hexHash(encoded); }//from ww w. ja v a 2 s .c om return null; }
From source file:org.xipki.commons.security.shell.CertRequestGenCommandSupport.java
License:Open Source License
@Override protected Object doExecute() throws Exception { hashAlgo = hashAlgo.trim().toUpperCase(); if (hashAlgo.indexOf('-') != -1) { hashAlgo = hashAlgo.replaceAll("-", ""); }//from w ww. j a v a 2s . c o m if (needExtensionTypes == null) { needExtensionTypes = new LinkedList<>(); } if (wantExtensionTypes == null) { wantExtensionTypes = new LinkedList<>(); } // SubjectAltNames List<Extension> extensions = new LinkedList<>(); ASN1OctetString extnValue = createExtnValueSubjectAltName(); if (extnValue != null) { ASN1ObjectIdentifier oid = Extension.subjectAlternativeName; extensions.add(new Extension(oid, false, extnValue)); needExtensionTypes.add(oid.getId()); } // SubjectInfoAccess extnValue = createExtnValueSubjectInfoAccess(); if (extnValue != null) { ASN1ObjectIdentifier oid = Extension.subjectInfoAccess; extensions.add(new Extension(oid, false, extnValue)); needExtensionTypes.add(oid.getId()); } // Keyusage if (isNotEmpty(keyusages)) { Set<KeyUsage> usages = new HashSet<>(); for (String usage : keyusages) { usages.add(KeyUsage.getKeyUsage(usage)); } org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages); ASN1ObjectIdentifier extType = Extension.keyUsage; extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // ExtendedKeyusage if (isNotEmpty(extkeyusages)) { ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages)); ASN1ObjectIdentifier extType = Extension.extendedKeyUsage; extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // QcEuLimitValue if (isNotEmpty(qcEuLimits)) { ASN1EncodableVector vec = new ASN1EncodableVector(); for (String m : qcEuLimits) { StringTokenizer st = new StringTokenizer(m, ":"); try { String currencyS = st.nextToken(); String amountS = st.nextToken(); String exponentS = st.nextToken(); Iso4217CurrencyCode currency; try { int intValue = Integer.parseInt(currencyS); currency = new Iso4217CurrencyCode(intValue); } catch (NumberFormatException ex) { currency = new Iso4217CurrencyCode(currencyS); } int amount = Integer.parseInt(amountS); int exponent = Integer.parseInt(exponentS); MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent); QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue, monterayValue); vec.add(statment); } catch (Exception ex) { throw new Exception("invalid qc-eu-limit '" + m + "'"); } } ASN1ObjectIdentifier extType = Extension.qCStatements; ASN1Sequence extValue = new DERSequence(vec); extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } // biometricInfo if (biometricType != null && biometricHashAlgo != null && biometricFile != null) { TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType) ? new TypeOfBiometricData(Integer.parseInt(biometricType)) : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType)); ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo); byte[] biometricBytes = IoUtil.read(biometricFile); MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId()); md.reset(); byte[] tmpBiometricDataHash = md.digest(biometricBytes); DERIA5String tmpSourceDataUri = null; if (biometricUri != null) { tmpSourceDataUri = new DERIA5String(biometricUri); } BiometricData biometricData = new BiometricData(tmpBiometricType, new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash), tmpSourceDataUri); ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(biometricData); ASN1ObjectIdentifier extType = Extension.biometricInfo; ASN1Sequence extValue = new DERSequence(vec); extensions.add(new Extension(extType, false, extValue.getEncoded())); needExtensionTypes.add(extType.getId()); } else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) { // Do nothing } else { throw new Exception("either all of biometric triples (type, hash algo, file)" + " must be set or none of them should be set"); } for (Extension addExt : getAdditionalExtensions()) { extensions.add(addExt); } needExtensionTypes.addAll(getAdditionalNeedExtensionTypes()); wantExtensionTypes.addAll(getAdditionalWantExtensionTypes()); if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) { ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes), textToAsn1ObjectIdentifers(wantExtensionTypes)); extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false, ee.toASN1Primitive().getEncoded())); } ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain)); Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>(); if (CollectionUtil.isNonEmpty(extensions)) { attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new Extensions(extensions.toArray(new Extension[0]))); } if (StringUtil.isNotBlank(challengePassword)) { attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword)); } SubjectPublicKeyInfo subjectPublicKeyInfo; if (signer.getCertificate() != null) { Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded()); subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo(); } else { subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey()); } X500Name subjectDn = getSubject(subject); PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes); File file = new File(outputFilename); saveVerbose("saved CSR to file", file, csr.getEncoded()); return null; }
From source file:org.xipki.commons.security.shell.ExtractCertFromCrlCmd.java
License:Open Source License
@Override protected Object doExecute() throws Exception { X509CRL crl = X509Util.parseCrl(crlFile); String oidExtnCerts = ObjectIdentifiers.id_xipki_ext_crlCertset.getId(); byte[] extnValue = crl.getExtensionValue(oidExtnCerts); if (extnValue == null) { throw new IllegalCmdParamException("no certificate is contained in " + crlFile); }/*from w w w . ja v a2 s. c o m*/ extnValue = removingTagAndLenFromExtensionValue(extnValue); ASN1Set asn1Set = DERSet.getInstance(extnValue); final int n = asn1Set.size(); if (n == 0) { throw new CmdFailure("no certificate is contained in " + crlFile); } ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out); for (int i = 0; i < n; i++) { ASN1Encodable asn1 = asn1Set.getObjectAt(i); Certificate cert; try { ASN1Sequence seq = ASN1Sequence.getInstance(asn1); cert = Certificate.getInstance(seq.getObjectAt(0)); } catch (IllegalArgumentException ex) { // backwards compatibility cert = Certificate.getInstance(asn1); } byte[] certBytes = cert.getEncoded(); String sha1FpCert = HashAlgoType.SHA1.hexHash(certBytes); ZipEntry certZipEntry = new ZipEntry(sha1FpCert + ".der"); zip.putNextEntry(certZipEntry); try { zip.write(certBytes); } finally { zip.closeEntry(); } } zip.flush(); zip.close(); saveVerbose("extracted " + n + " certificates to", new File(outFile), out.toByteArray()); return null; }
From source file:org.xipki.dbtool.CaCertStoreDbImporter.java
License:Open Source License
private int[] do_import_cert(final PreparedStatement ps_cert, final PreparedStatement ps_rawcert, final String certsZipFile, final int minId, final File processLogFile, final int totalProcessedSum) throws IOException, JAXBException, DataAccessException, CertificateException { ZipFile zipFile = new ZipFile(new File(baseDir, certsZipFile)); ZipEntry certsXmlEntry = zipFile.getEntry("certs.xml"); CertsType certs;//w ww . jav a 2 s. c o m try { @SuppressWarnings("unchecked") JAXBElement<CertsType> rootElement = (JAXBElement<CertsType>) unmarshaller .unmarshal(zipFile.getInputStream(certsXmlEntry)); certs = rootElement.getValue(); } catch (JAXBException e) { try { zipFile.close(); } catch (Exception e2) { } throw XMLUtil.convert(e); } disableAutoCommit(); try { List<CertType> list = certs.getCert(); final int size = list.size(); final int n = 100; int numProcessed = 0; int numEntriesInBatch = 0; int lastSuccessfulCertId = 0; for (int i = 0; i < size; i++) { CertType cert = list.get(i); int id = cert.getId(); lastSuccessfulCertId = id; if (id < minId) { continue; } int certArt = cert.getArt() == null ? 1 : cert.getArt(); numEntriesInBatch++; String filename = cert.getCertFile(); // rawcert ZipEntry certZipEnty = zipFile.getEntry(filename); // rawcert byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty)); Certificate c; try { c = Certificate.getInstance(encodedCert); } catch (Exception e) { LOG.error("could not parse certificate in file {}", filename); LOG.debug("could not parse certificate in file " + filename, e); if (e instanceof CertificateException) { throw (CertificateException) e; } else { throw new CertificateException(e.getMessage(), e); } } byte[] encodedKey = c.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); String hexSha1FpCert = HashCalculator.hexHash(HashAlgoType.SHA1, encodedCert); // cert try { int idx = 1; ps_cert.setInt(idx++, id); ps_cert.setInt(idx++, certArt); ps_cert.setLong(idx++, cert.getLastUpdate()); ps_cert.setLong(idx++, c.getSerialNumber().getPositiveValue().longValue()); ps_cert.setString(idx++, X509Util.getRFC4519Name(c.getSubject())); ps_cert.setLong(idx++, c.getTBSCertificate().getStartDate().getDate().getTime() / 1000); ps_cert.setLong(idx++, c.getTBSCertificate().getEndDate().getDate().getTime() / 1000); setBoolean(ps_cert, idx++, cert.isRevoked()); setInt(ps_cert, idx++, cert.getRevReason()); setLong(ps_cert, idx++, cert.getRevTime()); setLong(ps_cert, idx++, cert.getRevInvTime()); setInt(ps_cert, idx++, cert.getProfileId()); setInt(ps_cert, idx++, cert.getCaId()); setInt(ps_cert, idx++, cert.getRequestorId()); setInt(ps_cert, idx++, cert.getUserId()); ps_cert.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedKey)); String sha1FpSubject = X509Util.sha1sum_canonicalized_name(c.getSubject()); ps_cert.setString(idx++, sha1FpSubject); Extension extension = c.getTBSCertificate().getExtensions() .getExtension(Extension.basicConstraints); boolean ee = true; if (extension != null) { ASN1Encodable asn1 = extension.getParsedValue(); try { ee = BasicConstraints.getInstance(asn1).isCA() == false; } catch (Exception e) { } } ps_cert.setInt(idx++, ee ? 1 : 0); ps_cert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_CERT, e); } try { int idx = 1; ps_rawcert.setInt(idx++, cert.getId()); ps_rawcert.setString(idx++, hexSha1FpCert); ps_rawcert.setString(idx++, Base64.toBase64String(encodedCert)); ps_rawcert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_RAWCERT, e); } if (numEntriesInBatch > 0 && (numEntriesInBatch % n == 0 || i == size - 1)) { String sql = null; try { sql = SQL_ADD_CERT; ps_cert.executeBatch(); sql = SQL_ADD_RAWCERT; ps_rawcert.executeBatch(); sql = null; commit("(commit import cert to CA)"); } catch (SQLException e) { rollback(); throw translate(sql, e); } catch (DataAccessException e) { rollback(); throw e; } numProcessed += numEntriesInBatch; numEntriesInBatch = 0; echoToFile((totalProcessedSum + numProcessed) + ":" + lastSuccessfulCertId, processLogFile); } } return new int[] { numProcessed, lastSuccessfulCertId }; } finally { try { recoverAutoCommit(); } catch (DataAccessException e) { } zipFile.close(); } }
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 {//w ww. j av a 2 s . c o m 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.ja v a 2 s .c om*/ 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.ocsp.server.impl.certstore.CrlCertStatusStore.java
License:Open Source License
private synchronized void initializeStore(final boolean force) { Boolean updateCRLSuccessfull = null; try {//from w w w . j a va 2s . c o m File fullCrlFile = new File(crlFilename); if (fullCrlFile.exists() == false) { // file does not exist LOG.warn("CRL File {} does not exist", crlFilename); return; } long newLastModifed = fullCrlFile.lastModified(); boolean deltaCrlExists; File deltaCrlFile = null; if (deltaCrlFilename != null) { deltaCrlFile = new File(deltaCrlFilename); deltaCrlExists = deltaCrlFile.exists(); } else { deltaCrlExists = false; } long newLastModifedOfDeltaCrl = deltaCrlExists ? deltaCrlFile.lastModified() : 0; if (force == false) { long now = System.currentTimeMillis(); if (newLastModifed != lastmodifiedOfCrlFile) { if (now - newLastModifed < 5000) { return; // still in copy process } } if (deltaCrlExists) { if (newLastModifedOfDeltaCrl != lastModifiedOfDeltaCrlFile) { if (now - newLastModifed < 5000) { return; // still in copy process } } } } // end if(force) byte[] newFp = sha1Fp(fullCrlFile); boolean crlFileChanged = Arrays.equals(newFp, fpOfCrlFile) == false; if (crlFileChanged == false) { auditLogPCIEvent(AuditLevel.INFO, "UPDATE_CERTSTORE", "current CRL is still up-to-date"); return; } byte[] newFpOfDeltaCrl = deltaCrlExists ? sha1Fp(deltaCrlFile) : null; boolean deltaCrlFileChanged = Arrays.equals(newFpOfDeltaCrl, fpOfDeltaCrlFile) == false; if (crlFileChanged == false && deltaCrlFileChanged == false) { return; } if (crlFileChanged) { LOG.info("CRL file {} has changed, updating of the CertStore required", crlFilename); } if (deltaCrlFileChanged) { LOG.info("DeltaCRL file {} has changed, updating of the CertStore required", deltaCrlFilename); } auditLogPCIEvent(AuditLevel.INFO, "UPDATE_CERTSTORE", "a newer version of CRL is available"); updateCRLSuccessfull = false; X509CRL crl = X509Util.parseCRL(crlFilename); BigInteger crlNumber; { byte[] octetString = crl.getExtensionValue(Extension.cRLNumber.getId()); if (octetString != null) { byte[] extnValue = DEROctetString.getInstance(octetString).getOctets(); crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue(); } else { crlNumber = null; } } X500Principal issuer = crl.getIssuerX500Principal(); boolean caAsCrlIssuer = true; if (caCert.getSubjectX500Principal().equals(issuer) == false) { caAsCrlIssuer = false; if (issuerCert == null) { throw new IllegalArgumentException("issuerCert could not be null"); } if (issuerCert.getSubjectX500Principal().equals(issuer) == false) { throw new IllegalArgumentException("The issuerCert and CRL do not match"); } } X509Certificate crlSignerCert = caAsCrlIssuer ? caCert : issuerCert; try { crl.verify(crlSignerCert.getPublicKey()); } catch (Exception e) { throw new CertStatusStoreException(e.getMessage(), e); } X509CRL deltaCrl = null; BigInteger deltaCrlNumber = null; BigInteger baseCrlNumber = null; if (deltaCrlExists) { if (crlNumber == null) { throw new CertStatusStoreException("baseCRL does not contains CRLNumber"); } deltaCrl = X509Util.parseCRL(deltaCrlFilename); byte[] octetString = deltaCrl.getExtensionValue(Extension.deltaCRLIndicator.getId()); if (octetString == null) { deltaCrl = null; LOG.warn("{} is a full CRL instead of delta CRL, ignore it", deltaCrlFilename); } else { byte[] extnValue = DEROctetString.getInstance(octetString).getOctets(); baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue(); if (baseCrlNumber.equals(crlNumber) == false) { deltaCrl = null; LOG.info("{} is not a deltaCRL for the CRL {}, ignore it", deltaCrlFilename, crlFilename); } else { octetString = deltaCrl.getExtensionValue(Extension.cRLNumber.getId()); extnValue = DEROctetString.getInstance(octetString).getOctets(); deltaCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue(); } } } if (crlFileChanged == false && deltaCrl == null) { return; } Date newThisUpdate; Date newNextUpdate; if (deltaCrl != null) { LOG.info("try to update CRL with CRLNumber={} and DeltaCRL with CRLNumber={}", crlNumber, deltaCrlNumber); newThisUpdate = deltaCrl.getThisUpdate(); newNextUpdate = deltaCrl.getNextUpdate(); } else { newThisUpdate = crl.getThisUpdate(); newNextUpdate = crl.getNextUpdate(); } // Construct CrlID ASN1EncodableVector v = new ASN1EncodableVector(); if (StringUtil.isNotBlank(crlUrl)) { v.add(new DERTaggedObject(true, 0, new DERIA5String(crlUrl, true))); } byte[] extValue = (deltaCrlExists ? deltaCrl : crl).getExtensionValue(Extension.cRLNumber.getId()); if (extValue != null) { ASN1Integer asn1CrlNumber = ASN1Integer.getInstance(removeTagAndLenFromExtensionValue(extValue)); v.add(new DERTaggedObject(true, 1, asn1CrlNumber)); } v.add(new DERTaggedObject(true, 2, new DERGeneralizedTime(newThisUpdate))); this.crlID = CrlID.getInstance(new DERSequence(v)); byte[] encodedCaCert; try { encodedCaCert = caCert.getEncoded(); } catch (CertificateEncodingException e) { throw new CertStatusStoreException(e.getMessage(), e); } Certificate bcCaCert = Certificate.getInstance(encodedCaCert); byte[] encodedName; try { encodedName = bcCaCert.getSubject().getEncoded("DER"); } catch (IOException e) { throw new CertStatusStoreException(e.getMessage(), e); } byte[] encodedKey = bcCaCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); Map<HashAlgoType, IssuerHashNameAndKey> newIssuerHashMap = new ConcurrentHashMap<>(); for (HashAlgoType hashAlgo : HashAlgoType.values()) { byte[] issuerNameHash = HashCalculator.hash(hashAlgo, encodedName); byte[] issuerKeyHash = HashCalculator.hash(hashAlgo, encodedKey); IssuerHashNameAndKey issuerHash = new IssuerHashNameAndKey(hashAlgo, issuerNameHash, issuerKeyHash); newIssuerHashMap.put(hashAlgo, issuerHash); } X500Name caName = X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()); // extract the certificate, only in full CRL, not in delta CRL boolean certsIncluded = false; Set<CertWithInfo> certs = new HashSet<>(); String oidExtnCerts = ObjectIdentifiers.id_xipki_ext_crlCertset.getId(); byte[] extnValue = crl.getExtensionValue(oidExtnCerts); if (extnValue == null) { // try the legacy OID extnValue = crl.getExtensionValue("1.3.6.1.4.1.12655.100"); } if (extnValue != null) { extnValue = removeTagAndLenFromExtensionValue(extnValue); certsIncluded = true; ASN1Set asn1Set = DERSet.getInstance(extnValue); int n = asn1Set.size(); for (int i = 0; i < n; i++) { ASN1Encodable asn1 = asn1Set.getObjectAt(i); Certificate bcCert; String profileName = null; try { ASN1Sequence seq = ASN1Sequence.getInstance(asn1); bcCert = Certificate.getInstance(seq.getObjectAt(0)); if (seq.size() > 1) { profileName = DERUTF8String.getInstance(seq.getObjectAt(1)).getString(); } } catch (IllegalArgumentException e) { // backwards compatibility bcCert = Certificate.getInstance(asn1); } if (caName.equals(bcCert.getIssuer()) == false) { throw new CertStatusStoreException("invalid entry in CRL Extension certs"); } if (profileName == null) { profileName = "UNKNOWN"; } certs.add(new CertWithInfo(bcCert, profileName)); } } if (certsDirname != null) { if (extnValue != null) { LOG.warn("ignore certsDir '{}', since certificates are included in CRL Extension certs", certsDirname); } else { certsIncluded = true; Set<CertWithInfo> tmpCerts = readCertWithInfosFromDir(caCert, certsDirname); certs.addAll(tmpCerts); } } Map<BigInteger, CrlCertStatusInfo> newCertStatusInfoMap = new ConcurrentHashMap<>(); // First consider only full CRL Set<? extends X509CRLEntry> revokedCertListInFullCRL = crl.getRevokedCertificates(); if (revokedCertListInFullCRL != null) { for (X509CRLEntry revokedCert : revokedCertListInFullCRL) { X500Principal thisIssuer = revokedCert.getCertificateIssuer(); if (thisIssuer != null && caCert.getSubjectX500Principal().equals(thisIssuer) == false) { throw new CertStatusStoreException("invalid CRLEntry"); } } } Set<? extends X509CRLEntry> revokedCertListInDeltaCRL = null; if (deltaCrl != null) { revokedCertListInDeltaCRL = deltaCrl.getRevokedCertificates(); if (revokedCertListInDeltaCRL != null) { for (X509CRLEntry revokedCert : revokedCertListInDeltaCRL) { X500Principal thisIssuer = revokedCert.getCertificateIssuer(); if (thisIssuer != null && caCert.getSubjectX500Principal().equals(thisIssuer) == false) { throw new CertStatusStoreException("invalid CRLEntry"); } } } } Map<BigInteger, X509CRLEntry> revokedCertMap = null; // merge the revoked list if (CollectionUtil.isNotEmpty(revokedCertListInDeltaCRL)) { revokedCertMap = new HashMap<BigInteger, X509CRLEntry>(); for (X509CRLEntry entry : revokedCertListInFullCRL) { revokedCertMap.put(entry.getSerialNumber(), entry); } for (X509CRLEntry entry : revokedCertListInDeltaCRL) { BigInteger serialNumber = entry.getSerialNumber(); java.security.cert.CRLReason reason = entry.getRevocationReason(); if (reason == java.security.cert.CRLReason.REMOVE_FROM_CRL) { revokedCertMap.remove(serialNumber); } else { revokedCertMap.put(serialNumber, entry); } } } Iterator<? extends X509CRLEntry> it = null; if (revokedCertMap != null) { it = revokedCertMap.values().iterator(); } else if (revokedCertListInFullCRL != null) { it = revokedCertListInFullCRL.iterator(); } if (it != null) { while (it.hasNext()) { X509CRLEntry revokedCert = it.next(); BigInteger serialNumber = revokedCert.getSerialNumber(); byte[] encodedExtnValue = revokedCert.getExtensionValue(Extension.reasonCode.getId()); int reasonCode; if (encodedExtnValue != null) { ASN1Enumerated enumerated = ASN1Enumerated .getInstance(removeTagAndLenFromExtensionValue(encodedExtnValue)); reasonCode = enumerated.getValue().intValue(); } else { reasonCode = CRLReason.UNSPECIFIED.getCode(); } Date revTime = revokedCert.getRevocationDate(); Date invalidityTime = null; extnValue = revokedCert.getExtensionValue(Extension.invalidityDate.getId()); if (extnValue != null) { extnValue = removeTagAndLenFromExtensionValue(extnValue); ASN1GeneralizedTime gTime = DERGeneralizedTime.getInstance(extnValue); try { invalidityTime = gTime.getDate(); } catch (ParseException e) { throw new CertStatusStoreException(e.getMessage(), e); } if (revTime.equals(invalidityTime)) { invalidityTime = null; } } CertWithInfo cert = null; if (certsIncluded) { for (CertWithInfo bcCert : certs) { if (bcCert.cert.getIssuer().equals(caName) && bcCert.cert.getSerialNumber().getPositiveValue().equals(serialNumber)) { cert = bcCert; break; } } if (cert == null) { LOG.info("could not find certificate (issuer = '{}', serialNumber = '{}'", X509Util.getRFC4519Name(caName), serialNumber); } else { certs.remove(cert); } } Map<HashAlgoType, byte[]> certHashes = (cert == null) ? null : getCertHashes(cert.cert); CertRevocationInfo revocationInfo = new CertRevocationInfo(reasonCode, revTime, invalidityTime); CrlCertStatusInfo crlCertStatusInfo = CrlCertStatusInfo.getRevokedCertStatusInfo(revocationInfo, (cert == null) ? null : cert.profileName, certHashes); newCertStatusInfoMap.put(serialNumber, crlCertStatusInfo); } // end while(it.hasNext()) } // end if(it) for (CertWithInfo cert : certs) { Map<HashAlgoType, byte[]> certHashes = getCertHashes(cert.cert); CrlCertStatusInfo crlCertStatusInfo = CrlCertStatusInfo.getGoodCertStatusInfo(cert.profileName, certHashes); newCertStatusInfoMap.put(cert.cert.getSerialNumber().getPositiveValue(), crlCertStatusInfo); } this.initialized = false; this.lastmodifiedOfCrlFile = newLastModifed; this.fpOfCrlFile = newFp; this.lastModifiedOfDeltaCrlFile = newLastModifedOfDeltaCrl; this.fpOfDeltaCrlFile = newFpOfDeltaCrl; this.issuerHashMap.clear(); this.issuerHashMap.putAll(newIssuerHashMap); this.certStatusInfoMap.clear(); this.certStatusInfoMap.putAll(newCertStatusInfoMap); this.thisUpdate = newThisUpdate; this.nextUpdate = newNextUpdate; this.initializationFailed = false; this.initialized = true; updateCRLSuccessfull = true; LOG.info("updated CertStore {}", getName()); } catch (Exception e) { final String message = "could not execute initializeStore()"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); initializationFailed = true; initialized = true; } finally { if (updateCRLSuccessfull != null) { AuditLevel auditLevel; AuditStatus auditStatus; String eventType = "UPDATE_CRL"; if (updateCRLSuccessfull) { auditLevel = AuditLevel.INFO; auditStatus = AuditStatus.FAILED; } else { auditLevel = AuditLevel.ERROR; auditStatus = AuditStatus.SUCCESSFUL; } auditLogPCIEvent(auditLevel, eventType, auditStatus.name()); } } }
From source file:org.xipki.ocsp.server.impl.certstore.CrlCertStatusStore.java
License:Open Source License
private Set<CertWithInfo> readCertWithInfosFromDir(final X509Certificate caCert, final String certsDirname) throws CertificateEncodingException { File certsDir = new File(certsDirname); if (certsDir.exists() == false) { LOG.warn("the folder " + certsDirname + " does not exist, ignore it"); return Collections.emptySet(); }/*w ww.ja v a 2s . c o m*/ if (certsDir.isDirectory() == false) { LOG.warn("the path " + certsDirname + " does not point to a folder, ignore it"); return Collections.emptySet(); } if (certsDir.canRead() == false) { LOG.warn("the folder " + certsDirname + " could not be read, ignore it"); return Collections.emptySet(); } File[] certFiles = certsDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".der") || name.endsWith(".crt"); } }); if (certFiles == null || certFiles.length == 0) { return Collections.emptySet(); } X500Name issuer = X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()); byte[] issuerSKI = X509Util.extractSKI(caCert); Set<CertWithInfo> certs = new HashSet<>(); final String profileName = "UNKNOWN"; for (File certFile : certFiles) { Certificate bcCert; try { byte[] encoded = IoUtil.read(certFile); bcCert = Certificate.getInstance(encoded); } catch (IllegalArgumentException | IOException e) { LOG.warn("could not parse certificate {}, ignore it", certFile.getPath()); continue; } // not issued by the given issuer if (issuer.equals(bcCert.getIssuer()) == false) { continue; } if (issuerSKI != null) { byte[] aki = null; try { aki = X509Util.extractAKI(bcCert); } catch (CertificateEncodingException e) { final String message = "could not extract AuthorityKeyIdentifier"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); } if (aki == null || Arrays.equals(issuerSKI, aki) == false) { continue; } } certs.add(new CertWithInfo(bcCert, profileName)); } return certs; }
From source file:org.xipki.pki.ca.client.shell.loadtest.CaLoadTestRevokeCmd.java
License:Open Source License
@Override protected Object doExecute() throws Exception { if (numThreads < 1) { throw new IllegalCmdParamException("invalid number of threads " + numThreads); }/*from ww w . j a v a 2 s . c o m*/ if (!(serialNumberFile == null ^ caDbConfFile == null)) { throw new IllegalCmdParamException("exactly one of ca-db and serial-file must be specified"); } StringBuilder description = new StringBuilder(200); description.append("issuer: ").append(issuerCertFile).append("\n"); description.append("cadb: ").append(caDbConfFile).append("\n"); description.append("serialNumberFile: ").append(serialNumberFile).append("\n"); description.append("maxCerts: ").append(maxCerts).append("\n"); description.append("#certs/req: ").append(num).append("\n"); description.append("unit: ").append(num).append(" certificate"); if (num > 1) { description.append("s"); } description.append("\n"); Certificate caCert = Certificate.getInstance(IoUtil.read(issuerCertFile)); Properties props = new Properties(); props.load(new FileInputStream(IoUtil.expandFilepath(caDbConfFile))); props.setProperty("autoCommit", "false"); props.setProperty("readOnly", "true"); props.setProperty("maximumPoolSize", "1"); props.setProperty("minimumIdle", "1"); DataSourceWrapper caDataSource = null; Iterator<BigInteger> serialNumberIterator; if (caDbConfFile != null) { caDataSource = new DataSourceFactory().createDataSource("ds-" + caDbConfFile, props, securityFactory.getPasswordResolver()); serialNumberIterator = new DbGoodCertSerialIterator(caCert, caDataSource); } else { serialNumberIterator = new FileBigIntegerIterator(serialNumberFile, hex, false); } try { CaLoadTestRevoke loadTest = new CaLoadTestRevoke(caClient, caCert, serialNumberIterator, maxCerts, num, description.toString()); loadTest.setDuration(duration); loadTest.setThreads(numThreads); loadTest.test(); } finally { if (caDataSource != null) { caDataSource.shutdown(); } if (serialNumberIterator instanceof FileBigIntegerIterator) { ((FileBigIntegerIterator) serialNumberIterator).close(); } } return null; }
From source file:org.xipki.pki.ca.dbtool.diffdb.EjbcaDigestExporter.java
License:Open Source License
private void doDigestNoTableId(final ProcessLog processLog, final CaEntryContainer caEntryContainer, final Map<String, EjbcaCaInfo> caInfos) throws Exception { int skippedAccount = 0; String lastProcessedHexCertFp; lastProcessedHexCertFp = Hex.toHexString(new byte[20]); // 40 zeros System.out.println("digesting certificates from fingerprint (exclusive)\n\t" + lastProcessedHexCertFp); PreparedStatement ps = prepareStatement(sql); PreparedStatement rawCertPs = prepareStatement(certSql); processLog.printHeader();//from www . ja v a 2s . c om String tmpSql = null; int id = 0; try { boolean interrupted = false; String hexCertFp = lastProcessedHexCertFp; while (true) { if (stopMe.get()) { interrupted = true; break; } ps.setString(1, hexCertFp); ResultSet rs = ps.executeQuery(); int countEntriesInResultSet = 0; while (rs.next()) { id++; countEntriesInResultSet++; String hexCaFp = rs.getString("cAFingerprint"); hexCertFp = rs.getString("fingerprint"); EjbcaCaInfo caInfo = null; if (!hexCaFp.equals(hexCertFp)) { caInfo = caInfos.get(hexCaFp); } if (caInfo == null) { LOG.debug("Found no CA by cAFingerprint, try to resolve by issuer"); rawCertPs.setString(1, hexCertFp); ResultSet certRs = rawCertPs.executeQuery(); if (certRs.next()) { String b64Cert = certRs.getString("base64Cert"); Certificate cert = Certificate.getInstance(Base64.decode(b64Cert)); for (EjbcaCaInfo entry : caInfos.values()) { if (entry.getSubject().equals(cert.getIssuer())) { caInfo = entry; break; } } } certRs.close(); } if (caInfo == null) { LOG.error("found no CA for Cert with fingerprint '{}'", hexCertFp); skippedAccount++; processLog.addNumProcessed(1); continue; } String hash = Base64.toBase64String(Hex.decode(hexCertFp)); String str = rs.getString("serialNumber"); BigInteger serial = new BigInteger(str); int status = rs.getInt("status"); boolean revoked = (status == EjbcaConstants.CERT_REVOKED || status == EjbcaConstants.CERT_TEMP_REVOKED); Integer revReason = null; Long revTime = null; Long revInvTime = null; if (revoked) { revReason = rs.getInt("revocationReason"); long revTimeInMs = rs.getLong("revocationDate"); // rev_time is milliseconds, convert it to seconds revTime = revTimeInMs / 1000; } DbDigestEntry cert = new DbDigestEntry(serial, revoked, revReason, revTime, revInvTime, hash); caEntryContainer.addDigestEntry(caInfo.getCaId(), id, cert); processLog.addNumProcessed(1); processLog.printStatus(); } // end while (rs.next()) rs.close(); if (countEntriesInResultSet == 0) { break; } } // end while (true) if (interrupted) { throw new InterruptedException("interrupted by the user"); } } catch (SQLException ex) { throw translate(tmpSql, ex); } finally { releaseResources(ps, null); releaseResources(rawCertPs, null); } processLog.printTrailer(); StringBuilder sb = new StringBuilder(200); sb.append(" digested ").append((processLog.getNumProcessed() - skippedAccount)).append(" certificates"); if (skippedAccount > 0) { sb.append(", ignored ").append(skippedAccount).append(" certificates (see log for details)"); } System.out.println(sb.toString()); }