List of usage examples for org.bouncycastle.asn1.x509 Certificate getInstance
public static Certificate getInstance(Object obj)
From source file:org.xipki.pki.ca.server.impl.store.CertStoreQueryExecutor.java
License:Open Source License
X509CertificateInfo getCertificateInfo(final X509Cert caCert, final BigInteger serial) throws DataAccessException, OperationException, CertificateException { ParamUtil.requireNonNull("caCert", caCert); ParamUtil.requireNonNull("serial", serial); int caId = getCaId(caCert); final String sql = sqls.sqlCertInfo; String b64Cert;/* ww w. j a v a2 s .c om*/ boolean revoked; int revReason = 0; long revTime = 0; long revInvTime = 0; int certprofileId = 0; ResultSet rs = null; PreparedStatement ps = borrowPreparedStatement(sql); try { int idx = 1; ps.setInt(idx++, caId); ps.setString(idx++, serial.toString(16)); rs = ps.executeQuery(); if (!rs.next()) { return null; } b64Cert = rs.getString("CERT"); certprofileId = rs.getInt("PID"); revoked = rs.getBoolean("REV"); if (revoked) { revReason = rs.getInt("RR"); revTime = rs.getLong("RT"); revInvTime = rs.getLong("RIT"); } } catch (SQLException ex) { throw datasource.translate(sql, ex); } finally { releaseDbResources(ps, rs); } try { byte[] encodedCert = Base64.decode(b64Cert); X509Certificate cert = X509Util.parseCert(encodedCert); String certprofileName = certprofileStore.getName(certprofileId); X509CertWithDbId certWithMeta = new X509CertWithDbId(cert, encodedCert); byte[] subjectPublicKeyInfo = Certificate.getInstance(encodedCert).getTBSCertificate() .getSubjectPublicKeyInfo().getEncoded(); X509CertificateInfo certInfo = new X509CertificateInfo(certWithMeta, caCert, subjectPublicKeyInfo, certprofileName); if (!revoked) { return certInfo; } Date invalidityTime = (revInvTime == 0) ? null : new Date(revInvTime * 1000); CertRevocationInfo revInfo = new CertRevocationInfo(revReason, new Date(revTime * 1000), invalidityTime); certInfo.setRevocationInfo(revInfo); return certInfo; } catch (IOException ex) { LOG.warn("getCertificateInfo()", ex); throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex); } }
From source file:org.xipki.pki.ca.server.impl.X509Ca.java
License:Open Source License
/** * Add XiPKI extension CrlCertSet.//w ww . ja va2 s. co m * * <pre> * Xipki-CrlCertSet ::= SET OF Xipki-CrlCert * * Xipki-CrlCert ::= SEQUENCE { * serial INTEGER * cert [0] EXPLICIT Certificate OPTIONAL * profileName [1] EXPLICIT UTF8String OPTIONAL * } * </pre> */ private void addXipkiCertset(final X509v2CRLBuilder crlBuilder, final boolean deltaCrl, final CrlControl control, final X509Cert caCert, final Date notExpireAt, final boolean onlyCaCerts, final boolean onlyUserCerts) throws OperationException { if (deltaCrl || !control.isXipkiCertsetIncluded()) { return; } ASN1EncodableVector vector = new ASN1EncodableVector(); final int numEntries = 100; long startId = 1; List<SerialWithId> serials; do { serials = certstore.getCertSerials(caCert, notExpireAt, startId, numEntries, false, onlyCaCerts, onlyUserCerts); long maxId = 1; for (SerialWithId sid : serials) { if (sid.getId() > maxId) { maxId = sid.getId(); } ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(new ASN1Integer(sid.getSerial())); String profileName = null; if (control.isXipkiCertsetCertIncluded()) { X509CertificateInfo certInfo; try { certInfo = certstore.getCertificateInfoForId(caCert, sid.getId()); } catch (CertificateException ex) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CertificateException: " + ex.getMessage()); } Certificate cert = Certificate.getInstance(certInfo.getCert().getEncodedCert()); vec.add(new DERTaggedObject(true, 0, cert)); if (control.isXipkiCertsetProfilenameIncluded()) { profileName = certInfo.getProfileName(); } } else if (control.isXipkiCertsetProfilenameIncluded()) { profileName = certstore.getCertProfileForId(caCert, sid.getId()); } if (StringUtil.isNotBlank(profileName)) { vec.add(new DERTaggedObject(true, 1, new DERUTF8String(profileName))); } vector.add(new DERSequence(vec)); } // end for startId = maxId + 1; } while (serials.size() >= numEntries); // end do try { crlBuilder.addExtension(ObjectIdentifiers.id_xipki_ext_crlCertset, false, new DERSet(vector)); } catch (CertIOException ex) { throw new OperationException(ErrorCode.INVALID_EXTENSION, "CertIOException: " + ex.getMessage()); } }
From source file:org.xipki.pki.ca.server.impl.X509CaInfo.java
License:Open Source License
public X509CaInfo(final X509CaEntry caEntry, final CertificateStore certStore) throws OperationException { this.caEntry = ParamUtil.requireNonNull("caEntry", caEntry); this.certStore = ParamUtil.requireNonNull("certStore", certStore); X509Certificate cert = caEntry.getCertificate(); this.notBefore = cert.getNotBefore(); this.notAfter = cert.getNotAfter(); this.serialNumber = cert.getSerialNumber(); this.selfSigned = cert.getIssuerX500Principal().equals(cert.getSubjectX500Principal()); Certificate bcCert;//from w w w .j a v a 2s. com try { byte[] encodedCert = cert.getEncoded(); bcCert = Certificate.getInstance(encodedCert); } catch (CertificateEncodingException ex) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not encode the CA certificate"); } this.certInCmpFormat = new CMPCertificate(bcCert); this.publicCaInfo = new PublicCaInfo(cert, caEntry.getCacertUris(), caEntry.getOcspUris(), caEntry.getCrlUris(), caEntry.getDeltaCrlUris()); this.noNewCertificateAfter = this.notAfter.getTime() - MS_PER_DAY * caEntry.getExpirationPeriod(); this.randomSnGenerator = RandomSerialNumberGenerator.getInstance(); }
From source file:org.xipki.pki.ca.server.impl.X509SelfSignedCertBuilder.java
License:Open Source License
public static GenerateSelfSignedResult generateSelfSigned(final SecurityFactory securityFactory, final String signerType, final String signerConf, final IdentifiedX509Certprofile certprofile, final CertificationRequest csr, final BigInteger serialNumber, final List<String> cacertUris, final List<String> ocspUris, final List<String> crlUris, final List<String> deltaCrlUris) throws OperationException, InvalidConfException { ParamUtil.requireNonNull("securityFactory", securityFactory); ParamUtil.requireNonBlank("signerType", signerType); ParamUtil.requireNonNull("certprofile", certprofile); ParamUtil.requireNonNull("csr", csr); ParamUtil.requireNonNull("serialNumber", serialNumber); if (serialNumber.compareTo(BigInteger.ZERO) != 1) { throw new IllegalArgumentException("serialNumber must not be non-positive: " + serialNumber); }/*from w w w . j ava 2s . co m*/ X509CertLevel level = certprofile.getCertLevel(); if (X509CertLevel.RootCA != level) { throw new IllegalArgumentException("certprofile is not of level " + X509CertLevel.RootCA); } if (!securityFactory.verifyPopo(csr, null)) { throw new InvalidConfException("could not validate POP for the CSR"); } if ("pkcs12".equalsIgnoreCase(signerType) || "jks".equalsIgnoreCase(signerType)) { ConfPairs keyValues = new ConfPairs(signerConf); String keystoreConf = keyValues.getValue("keystore"); if (keystoreConf == null) { throw new InvalidConfException( "required parameter 'keystore' for types PKCS12 and JKS, is not specified"); } } ConcurrentContentSigner signer; try { List<String[]> signerConfs = CaEntry.splitCaSignerConfs(signerConf); List<String> restrictedSigAlgos = certprofile.getSignatureAlgorithms(); String thisSignerConf = null; if (CollectionUtil.isEmpty(restrictedSigAlgos)) { thisSignerConf = signerConfs.get(0)[1]; } else { for (String algo : restrictedSigAlgos) { for (String[] m : signerConfs) { if (m[0].equals(algo)) { thisSignerConf = m[1]; break; } } if (thisSignerConf != null) { break; } } } if (thisSignerConf == null) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile"); } signer = securityFactory.createSigner(signerType, new SignerConf(thisSignerConf), (X509Certificate[]) null); } catch (XiSecurityException | ObjectCreationException ex) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex); } SubjectPublicKeyInfo publicKeyInfo; if (signer.getCertificate() != null) { // this cert is the dummy one which can be considered only as public key container Certificate bcCert; try { bcCert = Certificate.getInstance(signer.getCertificate().getEncoded()); } catch (Exception ex) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not reparse certificate: " + ex.getMessage()); } publicKeyInfo = bcCert.getSubjectPublicKeyInfo(); } else { PublicKey signerPublicKey = signer.getPublicKey(); try { publicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signerPublicKey); } catch (InvalidKeyException ex) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "cannot generate SubjectPublicKeyInfo from publicKey: " + ex.getMessage()); } } X509Certificate newCert = generateCertificate(signer, certprofile, csr, serialNumber, publicKeyInfo, cacertUris, ocspUris, crlUris, deltaCrlUris); return new GenerateSelfSignedResult(signerConf, newCert); }
From source file:org.xipki.pki.ocsp.client.shell.BaseOcspStatusCommandSupport.java
License:Open Source License
@Override protected final Object doExecute() throws Exception { if (StringUtil.isBlank(serialNumberList) && isEmpty(certFiles)) { throw new IllegalCmdParamException("Neither serialNumbers nor certFiles is set"); }//w w w .j av a 2 s.com X509Certificate issuerCert = X509Util.parseCert(issuerCertFile); Map<BigInteger, byte[]> encodedCerts = null; List<BigInteger> sns = new LinkedList<>(); if (isNotEmpty(certFiles)) { encodedCerts = new HashMap<>(certFiles.size()); String ocspUrl = null; X500Name issuerX500Name = null; if (isAttrCert) { issuerX500Name = X500Name.getInstance(issuerCert.getSubjectX500Principal().getEncoded()); } for (String certFile : certFiles) { BigInteger sn; List<String> ocspUrls; if (isAttrCert) { X509AttributeCertificateHolder cert = new X509AttributeCertificateHolder(IoUtil.read(certFile)); // no signature validation AttributeCertificateIssuer reqIssuer = cert.getIssuer(); if (reqIssuer != null && issuerX500Name != null) { X500Name reqIssuerName = reqIssuer.getNames()[0]; if (!issuerX500Name.equals(reqIssuerName)) { throw new IllegalCmdParamException( "certificate " + certFile + " is not issued by the given issuer"); } } ocspUrls = extractOcspUrls(cert); sn = cert.getSerialNumber(); } else { X509Certificate cert = X509Util.parseCert(certFile); if (!X509Util.issues(issuerCert, cert)) { throw new IllegalCmdParamException( "certificate " + certFile + " is not issued by the given issuer"); } ocspUrls = extractOcspUrls(cert); sn = cert.getSerialNumber(); } if (isBlank(serverUrl)) { if (CollectionUtil.isEmpty(ocspUrls)) { throw new IllegalCmdParamException("could not extract OCSP responder URL"); } else { String url = ocspUrls.get(0); if (ocspUrl != null && !ocspUrl.equals(url)) { throw new IllegalCmdParamException( "given certificates have different" + " OCSP responder URL in certificate"); } else { ocspUrl = url; } } } // end if sns.add(sn); byte[] encodedCert = IoUtil.read(certFile); encodedCerts.put(sn, encodedCert); } // end for if (isBlank(serverUrl)) { serverUrl = ocspUrl; } } else { StringTokenizer st = new StringTokenizer(serialNumberList, ", "); while (st.hasMoreTokens()) { String token = st.nextToken(); StringTokenizer st2 = new StringTokenizer(token, "-"); BigInteger from = toBigInt(st2.nextToken(), hex); BigInteger to = st2.hasMoreTokens() ? toBigInt(st2.nextToken(), hex) : null; if (to == null) { sns.add(from); } else { BigIntegerRange range = new BigIntegerRange(from, to); if (range.getDiff().compareTo(BigInteger.valueOf(10)) > 0) { throw new IllegalCmdParamException("to many serial numbers"); } BigInteger sn = range.getFrom(); while (range.isInRange(sn)) { sns.add(sn); sn = sn.add(BigInteger.ONE); } } } } if (isBlank(serverUrl)) { throw new IllegalCmdParamException("could not get URL for the OCSP responder"); } X509Certificate respIssuer = null; if (respIssuerFile != null) { respIssuer = X509Util.parseCert(IoUtil.expandFilepath(respIssuerFile)); } URL serverUrlObj = new URL(serverUrl); RequestOptions options = getRequestOptions(); checkParameters(respIssuer, sns, encodedCerts); boolean saveReq = isNotBlank(reqout); boolean saveResp = isNotBlank(respout); RequestResponseDebug debug = null; if (saveReq || saveResp) { debug = new RequestResponseDebug(); } IssuerHash issuerHash = new IssuerHash(HashAlgoType.getNonNullHashAlgoType(options.getHashAlgorithmId()), Certificate.getInstance(issuerCert.getEncoded())); OCSPResp response; try { response = requestor.ask(issuerCert, sns.toArray(new BigInteger[0]), serverUrlObj, options, debug); } finally { if (debug != null && debug.size() > 0) { RequestResponsePair reqResp = debug.get(0); if (saveReq) { byte[] bytes = reqResp.getRequest(); if (bytes != null) { IoUtil.save(reqout, bytes); } } if (saveResp) { byte[] bytes = reqResp.getResponse(); if (bytes != null) { IoUtil.save(respout, bytes); } } } // end if } // end finally return processResponse(response, respIssuer, issuerHash, sns, encodedCerts); }
From source file:org.xipki.pki.ocsp.server.impl.store.crl.CrlCertStatusStore.java
License:Open Source License
private synchronized void initializeStore(final boolean force) { Boolean updateCrlSuccessful = null; try {//from w ww. jav a2s. co m File fullCrlFile = new File(crlFilename); if (!fullCrlFile.exists()) { // file does not exist LOG.warn("CRL File {} does not exist", crlFilename); return; } long newLastModifed = fullCrlFile.lastModified(); long newLastModifedOfDeltaCrl; boolean deltaCrlExists; File deltaCrlFile = null; if (deltaCrlFilename != null) { deltaCrlFile = new File(deltaCrlFilename); deltaCrlExists = deltaCrlFile.exists(); newLastModifedOfDeltaCrl = deltaCrlExists ? deltaCrlFile.lastModified() : 0; } else { deltaCrlExists = false; newLastModifedOfDeltaCrl = 0; } if (!force) { long now = System.currentTimeMillis(); if (newLastModifed != lastmodifiedOfCrlFile && now - newLastModifed < 5000) { return; // still in copy process } if (deltaCrlExists) { if (newLastModifedOfDeltaCrl != lastModifiedOfDeltaCrlFile && now - newLastModifed < 5000) { return; // still in copy process } } } // end if (force) byte[] newFp = sha1Fp(fullCrlFile); boolean crlFileChanged = !Arrays.equals(newFp, fpOfCrlFile); byte[] newFpOfDeltaCrl = deltaCrlExists ? sha1Fp(deltaCrlFile) : null; boolean deltaCrlFileChanged = !Arrays.equals(newFpOfDeltaCrl, fpOfDeltaCrlFile); if (!crlFileChanged && !deltaCrlFileChanged) { return; } if (crlFileChanged) { LOG.info("CRL file {} has changed, update of the CertStore required", crlFilename); } if (deltaCrlFileChanged) { LOG.info("DeltaCRL file {} has changed, update of the CertStore required", deltaCrlFilename); } auditPciEvent(AuditLevel.INFO, "UPDATE_CERTSTORE", "a newer CRL is available"); updateCrlSuccessful = false; X509CRL crl = X509Util.parseCrl(crlFilename); byte[] octetString = crl.getExtensionValue(Extension.cRLNumber.getId()); if (octetString == null) { throw new OcspStoreException("CRL without CRLNumber is not supported"); } BigInteger newCrlNumber = ASN1Integer.getInstance(DEROctetString.getInstance(octetString).getOctets()) .getPositiveValue(); if (crlNumber != null && newCrlNumber.compareTo(crlNumber) <= 0) { throw new OcspStoreException( String.format("CRLNumber of new CRL (%s) <= current CRL (%s)", newCrlNumber, crlNumber)); } X500Principal issuer = crl.getIssuerX500Principal(); boolean caAsCrlIssuer = true; if (!caCert.getSubjectX500Principal().equals(issuer)) { caAsCrlIssuer = false; if (issuerCert == null) { throw new IllegalArgumentException("issuerCert must not be null"); } if (!issuerCert.getSubjectX500Principal().equals(issuer)) { throw new IllegalArgumentException("issuerCert and CRL do not match"); } } X509Certificate crlSignerCert = caAsCrlIssuer ? caCert : issuerCert; try { crl.verify(crlSignerCert.getPublicKey()); } catch (Exception ex) { throw new OcspStoreException(ex.getMessage(), ex); } X509CRL deltaCrl = null; BigInteger deltaCrlNumber = null; BigInteger baseCrlNumber = null; if (deltaCrlExists) { if (newCrlNumber == null) { throw new OcspStoreException("baseCRL does not contains CRLNumber"); } deltaCrl = X509Util.parseCrl(deltaCrlFilename); 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(newCrlNumber)) { 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(); } } // end if(octetString == null) } // end if(deltaCrlExists) Date newThisUpdate; Date newNextUpdate; if (deltaCrl != null) { LOG.info("try to update CRL with CRLNumber={} and DeltaCRL with CRLNumber={}", newCrlNumber, deltaCrlNumber); newThisUpdate = deltaCrl.getThisUpdate(); newNextUpdate = deltaCrl.getNextUpdate(); } else { newThisUpdate = crl.getThisUpdate(); newNextUpdate = crl.getNextUpdate(); } // Construct CrlID ASN1EncodableVector vec = new ASN1EncodableVector(); if (StringUtil.isNotBlank(crlUrl)) { vec.add(new DERTaggedObject(true, 0, new DERIA5String(crlUrl, true))); } byte[] extValue = ((deltaCrl != null) ? deltaCrl : crl).getExtensionValue(Extension.cRLNumber.getId()); if (extValue != null) { ASN1Integer asn1CrlNumber = ASN1Integer.getInstance(extractCoreValue(extValue)); vec.add(new DERTaggedObject(true, 1, asn1CrlNumber)); } vec.add(new DERTaggedObject(true, 2, new DERGeneralizedTime(newThisUpdate))); this.crlId = CrlID.getInstance(new DERSequence(vec)); byte[] encodedCaCert; try { encodedCaCert = caCert.getEncoded(); } catch (CertificateEncodingException ex) { throw new OcspStoreException(ex.getMessage(), ex); } Certificate bcCaCert = Certificate.getInstance(encodedCaCert); byte[] encodedName; try { encodedName = bcCaCert.getSubject().getEncoded("DER"); } catch (IOException ex) { throw new OcspStoreException(ex.getMessage(), ex); } byte[] encodedKey = bcCaCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); Map<HashAlgoType, IssuerHashNameAndKey> newIssuerHashMap = new ConcurrentHashMap<>(); for (HashAlgoType hashAlgo : HashAlgoType.values()) { byte[] issuerNameHash = hashAlgo.hash(encodedName); byte[] issuerKeyHash = hashAlgo.hash(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 String oidExtnCerts = ObjectIdentifiers.id_xipki_ext_crlCertset.getId(); byte[] extnValue = crl.getExtensionValue(oidExtnCerts); boolean certsConsidered = false; Map<BigInteger, CertWithInfo> certsMap; if (extnValue != null) { extnValue = extractCoreValue(extnValue); certsConsidered = true; certsMap = extractCertsFromExtCrlCertSet(extnValue, caName); } else { certsMap = new HashMap<>(); } if (certsDirname != null) { if (extnValue != null) { LOG.warn("ignore certsDir '{}', since certificates are included in {}", certsDirname, " CRL Extension certs"); } else { certsConsidered = true; readCertWithInfosFromDir(caCert, certsDirname, certsMap); } } 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 rcIssuer = revokedCert.getCertificateIssuer(); if (rcIssuer != null && !caCert.getSubjectX500Principal().equals(rcIssuer)) { throw new OcspStoreException("invalid CRLEntry"); } } } Set<? extends X509CRLEntry> revokedCertListInDeltaCrl = (deltaCrl == null) ? null : deltaCrl.getRevokedCertificates(); if (revokedCertListInDeltaCrl != null) { for (X509CRLEntry revokedCert : revokedCertListInDeltaCrl) { X500Principal rcIssuer = revokedCert.getCertificateIssuer(); if (rcIssuer != null && !caCert.getSubjectX500Principal().equals(rcIssuer)) { throw new OcspStoreException("invalid CRLEntry"); } } } Map<BigInteger, X509CRLEntry> revokedCertMap = null; // merge the revoked list if (revokedCertListInDeltaCrl != null && !revokedCertListInDeltaCrl.isEmpty()) { revokedCertMap = new HashMap<BigInteger, X509CRLEntry>(); if (revokedCertListInFullCrl != null) { for (X509CRLEntry entry : revokedCertListInFullCrl) { revokedCertMap.put(entry.getSerialNumber(), entry); } } for (X509CRLEntry entry : revokedCertListInDeltaCrl) { BigInteger serialNumber = entry.getSerialNumber(); CRLReason reason = entry.getRevocationReason(); if (reason == 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(); } while (it != null && 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(extractCoreValue(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 = extractCoreValue(extnValue); ASN1GeneralizedTime genTime = DERGeneralizedTime.getInstance(extnValue); try { invalidityTime = genTime.getDate(); } catch (ParseException ex) { throw new OcspStoreException(ex.getMessage(), ex); } if (revTime.equals(invalidityTime)) { invalidityTime = null; } } CertWithInfo cert = null; if (certsConsidered) { cert = certsMap.remove(serialNumber); if (cert == null && LOG.isInfoEnabled()) { LOG.info("could not find certificate (serialNumber='{}')", LogUtil.formatCsn(serialNumber)); } } Certificate bcCert = (cert == null) ? null : cert.getCert(); Map<HashAlgoType, byte[]> certHashes = (bcCert == null) ? null : getCertHashes(bcCert); Date notBefore = (bcCert == null) ? null : bcCert.getTBSCertificate().getStartDate().getDate(); Date notAfter = (bcCert == null) ? null : bcCert.getTBSCertificate().getEndDate().getDate(); CertRevocationInfo revocationInfo = new CertRevocationInfo(reasonCode, revTime, invalidityTime); String profileName = (cert == null) ? null : cert.getProfileName(); CrlCertStatusInfo crlCertStatusInfo = CrlCertStatusInfo.getRevokedCertStatusInfo(revocationInfo, profileName, certHashes, notBefore, notAfter); newCertStatusInfoMap.put(serialNumber, crlCertStatusInfo); } // end while for (BigInteger serialNumber : certsMap.keySet()) { CertWithInfo cert = certsMap.get(serialNumber); Certificate bcCert = cert.getCert(); Map<HashAlgoType, byte[]> certHashes = (bcCert == null) ? null : getCertHashes(bcCert); Date notBefore = (bcCert == null) ? null : bcCert.getTBSCertificate().getStartDate().getDate(); Date notAfter = (bcCert == null) ? null : bcCert.getTBSCertificate().getEndDate().getDate(); CrlCertStatusInfo crlCertStatusInfo = CrlCertStatusInfo.getGoodCertStatusInfo(cert.getProfileName(), certHashes, notBefore, notAfter); newCertStatusInfoMap.put(cert.getSerialNumber(), 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.crlNumber = newCrlNumber; this.initializationFailed = false; this.initialized = true; updateCrlSuccessful = true; LOG.info("updated CertStore {}", name); } catch (Exception ex) { LogUtil.error(LOG, ex, "could not execute initializeStore()"); initializationFailed = true; initialized = true; } finally { if (updateCrlSuccessful != null) { AuditLevel auditLevel = updateCrlSuccessful ? AuditLevel.INFO : AuditLevel.ERROR; AuditStatus auditStatus = updateCrlSuccessful ? AuditStatus.SUCCESSFUL : AuditStatus.FAILED; auditPciEvent(auditLevel, "UPDATE_CRL", auditStatus.name()); } } }
From source file:org.xipki.pki.ocsp.server.impl.store.crl.CrlCertStatusStore.java
License:Open Source License
private Map<BigInteger, CertWithInfo> extractCertsFromExtCrlCertSet(final byte[] encodedExtCrlCertSet, final X500Name caName) throws OcspStoreException { Map<BigInteger, CertWithInfo> certsMap = new HashMap<>(); ASN1Set asn1Set = DERSet.getInstance(encodedExtCrlCertSet); final int n = asn1Set.size(); for (int i = 0; i < n; i++) { ASN1Encodable asn1 = asn1Set.getObjectAt(i); ASN1Sequence seq = ASN1Sequence.getInstance(asn1); BigInteger serialNumber = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue(); Certificate bcCert = null; String profileName = null; final int size = seq.size(); for (int j = 1; j < size; j++) { ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(seq.getObjectAt(j)); int tagNo = taggedObj.getTagNo(); switch (tagNo) { case 0: bcCert = Certificate.getInstance(taggedObj.getObject()); break; case 1: profileName = DERUTF8String.getInstance(taggedObj.getObject()).getString(); break; default: break; }/*from ww w. j a v a 2s. c o m*/ } if (bcCert != null) { if (!caName.equals(bcCert.getIssuer())) { throw new OcspStoreException("issuer not match (serial=" + LogUtil.formatCsn(serialNumber) + ") in CRL Extension Xipki-CertSet"); } if (!serialNumber.equals(bcCert.getSerialNumber().getValue())) { throw new OcspStoreException("serialNumber not match (serial=" + LogUtil.formatCsn(serialNumber) + ") in CRL Extension Xipki-CertSet"); } } if (profileName == null) { profileName = "UNKNOWN"; } CertWithInfo entry = new CertWithInfo(serialNumber); entry.setProfileName(profileName); if (!certHashAlgos.isEmpty()) { entry.setCert(bcCert); } certsMap.put(serialNumber, entry); } return certsMap; }
From source file:org.xipki.pki.ocsp.server.impl.store.crl.CrlCertStatusStore.java
License:Open Source License
private void readCertWithInfosFromDir(final X509Certificate caCert, final String certsDirname, final Map<BigInteger, CertWithInfo> certsMap) throws CertificateEncodingException { File certsDir = new File(certsDirname); if (!certsDir.exists()) { LOG.warn("the folder " + certsDirname + " does not exist, ignore it"); return;//from www. jav a2s. c o m } if (!certsDir.isDirectory()) { LOG.warn("the path " + certsDirname + " does not point to a folder, ignore it"); return; } if (!certsDir.canRead()) { LOG.warn("the folder " + certsDirname + " must not be read, ignore it"); return; } File[] certFiles = certsDir.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return name.endsWith(".der") || name.endsWith(".crt"); } }); if (certFiles == null || certFiles.length == 0) { return; } X500Name issuer = X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()); byte[] issuerSki = X509Util.extractSki(caCert); final String profileName = "UNKNOWN"; final boolean needsCert = !certHashAlgos.isEmpty(); for (File certFile : certFiles) { Certificate bcCert; try { byte[] encoded = IoUtil.read(certFile); bcCert = Certificate.getInstance(encoded); } catch (IllegalArgumentException | IOException ex) { LOG.warn("could not parse certificate {}, ignore it", certFile.getPath()); continue; } BigInteger serialNumber = bcCert.getSerialNumber().getValue(); if (certsMap.containsKey(serialNumber)) { continue; } // not issued by the given issuer if (!issuer.equals(bcCert.getIssuer())) { continue; } if (issuerSki != null) { byte[] aki = null; try { aki = X509Util.extractAki(bcCert); } catch (CertificateEncodingException ex) { LogUtil.error(LOG, ex, "could not extract AuthorityKeyIdentifier"); } if (aki == null || !Arrays.equals(issuerSki, aki)) { continue; } } // end if CertWithInfo entry = new CertWithInfo(serialNumber); entry.setProfileName(profileName); if (needsCert) { entry.setCert(bcCert); } certsMap.put(serialNumber, entry); } // end for }
From source file:org.xipki.pki.ocsp.server.impl.store.db.DbCertStatusStore.java
License:Open Source License
private Map<HashAlgoType, IssuerHashNameAndKey> getIssuerHashAndKeys(byte[] encodedCert) throws CertificateEncodingException { byte[] encodedName; byte[] encodedKey; try {/*from w ww . ja v a2s. co m*/ Certificate bcCert = Certificate.getInstance(encodedCert); encodedName = bcCert.getSubject().getEncoded("DER"); encodedKey = bcCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); } catch (IllegalArgumentException | IOException ex) { throw new CertificateEncodingException(ex.getMessage(), ex); } Map<HashAlgoType, IssuerHashNameAndKey> hashes = new HashMap<>(); for (HashAlgoType ha : HashAlgoType.values()) { IssuerHashNameAndKey ih = new IssuerHashNameAndKey(ha, ha.hash(encodedName), ha.hash(encodedKey)); hashes.put(ha, ih); } return hashes; }
From source file:org.xipki.pki.scep.client.shell.GetCrlCmd.java
License:Open Source License
@Override protected Object doExecute() throws Exception { Certificate cert = Certificate.getInstance(IoUtil.read(certFile)); ScepClient client = getScepClient(); X509CRL crl = client.scepGetCrl(getIdentityKey(), getIdentityCert(), cert.getIssuer(), cert.getSerialNumber().getPositiveValue()); if (crl == null) { throw new CmdFailure("received no CRL from server"); }//from ww w .j av a 2s.c o m saveVerbose("saved CRL to file", new File(outputFile), crl.getEncoded()); return null; }