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

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

Introduction

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

Prototype

public X500Name getSubject() 

Source Link

Usage

From source file:org.xipki.pki.ca.client.shell.loadtest.CaLoadTestRevoke.java

License:Open Source License

public CaLoadTestRevoke(final CaClient caClient, final Certificate caCert,
        final Iterator<BigInteger> serialNumberIterator, final int maxCerts, final int num,
        final String description) throws Exception {
    super(description);
    ParamUtil.requireNonNull("caCert", caCert);
    this.num = ParamUtil.requireMin("num", num, 1);
    this.caClient = ParamUtil.requireNonNull("caClient", caClient);
    this.serialNumberIterator = ParamUtil.requireNonNull("serialNumberIterator", serialNumberIterator);
    this.caSubject = caCert.getSubject();
    this.maxCerts = maxCerts;
}

From source file:org.xipki.pki.ca.dbtool.diffdb.XipkiDigestExporter.java

License:Open Source License

private Map<Integer, String> getCaIds() throws DataAccessException, IOException {
    Map<Integer, String> caIdDirMap = new HashMap<>();
    final String sql = dbControl.getCaSql();

    Statement stmt = null;/*from   w ww  .j av a  2s. c  om*/
    ResultSet rs = null;
    try {
        stmt = createStatement();
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            String b64Cert = rs.getString("CERT");
            byte[] certBytes = Base64.decode(b64Cert);

            Certificate cert = Certificate.getInstance(certBytes);
            String commonName = X509Util.getCommonName(cert.getSubject());

            String fn = toAsciiFilename("ca-" + commonName);
            File caDir = new File(baseDir, fn);
            int idx = 2;
            while (caDir.exists()) {
                caDir = new File(baseDir, fn + "." + (idx++));
            }

            File caCertFile = new File(caDir, "ca.der");
            caDir.mkdirs();
            IoUtil.save(caCertFile, certBytes);

            int id = rs.getInt("ID");
            caIdDirMap.put(id, caDir.getName());
        }
    } catch (SQLException ex) {
        throw translate(sql, ex);
    } finally {
        releaseResources(stmt, rs);
    }

    return caIdDirMap;
}

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

License:Open Source License

private void importCa(final Cas cas) throws DataAccessException, CertificateException, IOException {
    final String sql = "INSERT INTO CS_CA (ID,SUBJECT,SHA1_CERT,CERT) VALUES (?,?,?,?)";
    System.out.println("importing table CS_CA");
    PreparedStatement ps = prepareStatement(sql);

    try {/*from   w  w w. j av a  2s  .  c  o  m*/
        for (CertstoreCaType m : cas.getCa()) {
            try {
                byte[] encodedCert = getBinary(m.getCert());
                Certificate cert = Certificate.getInstance(encodedCert);
                String b64Sha1FpCert = HashAlgoType.SHA1.base64Hash(encodedCert);

                int idx = 1;
                ps.setInt(idx++, (int) m.getId());
                ps.setString(idx++, X509Util.cutX500Name(cert.getSubject(), maxX500nameLen));
                ps.setString(idx++, b64Sha1FpCert);
                ps.setString(idx++, Base64.toBase64String(encodedCert));

                ps.execute();
            } catch (SQLException ex) {
                System.err.println(
                        "could not import CS_CA with ID=" + m.getId() + ", message: " + ex.getMessage());
                throw translate(sql, ex);
            } catch (IllegalArgumentException | IOException ex) {
                System.err.println(
                        "could not import CS_CA with ID=" + m.getId() + ", message: " + ex.getMessage());
                throw ex;
            }
        }
    } finally {
        releaseResources(ps, null);
    }

    System.out.println(" imported table CS_CA");
}

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

License:Open Source License

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

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

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

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

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

License:Open Source License

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

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

        if (ca == null) {
            return;
        }

        relatedCaIds.add(issuer.getId());

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

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

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

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

License:Open Source License

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

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

    Certificate bcCert;
    TBSCertificate tbsCert;/*from ww  w  .  j  a v  a2s  .c  o m*/
    X509Certificate cert;
    ValidationIssue issue;

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

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

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

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

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

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

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

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

        try {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return new ValidationResult(resultIssues);
}

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 ww w .  j ava  2  s. c om*/
        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.db.DbCertStatusStore.java

License:Open Source License

private Map<HashAlgoType, IssuerHashNameAndKey> getIssuerHashAndKeys(byte[] encodedCert)
        throws CertificateEncodingException {
    byte[] encodedName;
    byte[] encodedKey;
    try {//from  www .  j  a  va 2 s.  c o 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.serveremulator.CaEmulator.java

License:Open Source License

public CaEmulator(final PrivateKey caKey, final Certificate caCert, final boolean generateCrl)
        throws CertificateEncodingException {
    this.caKey = ParamUtil.requireNonNull("caKey", caKey);
    this.caCert = ParamUtil.requireNonNull("caCert", caCert);
    this.caSubject = caCert.getSubject();
    this.generateCrl = generateCrl;
    try {/*  w  w  w .  j a v a 2 s. c  om*/
        this.caCertBytes = caCert.getEncoded();
    } catch (IOException ex) {
        throw new CertificateEncodingException(ex.getMessage(), ex);
    }
}

From source file:org.xipki.security.shell.CertRequestGenCommand.java

License:Open Source License

@Override
protected Object _doExecute() throws Exception {
    P10RequestGenerator p10Gen = new P10RequestGenerator();

    hashAlgo = hashAlgo.trim().toUpperCase();
    if (hashAlgo.indexOf('-') != -1) {
        hashAlgo = hashAlgo.replaceAll("-", "");
    }/*from w  w  w. j  a  v  a  2s . c om*/

    if (needExtensionTypes == null) {
        needExtensionTypes = new LinkedList<>();
    }

    // SubjectAltNames
    List<Extension> extensions = new LinkedList<>();
    if (isNotEmpty(subjectAltNames)) {
        extensions.add(P10RequestGenerator.createExtensionSubjectAltName(subjectAltNames, false));
        needExtensionTypes.add(Extension.subjectAlternativeName.getId());
    }

    // SubjectInfoAccess
    if (isNotEmpty(subjectInfoAccesses)) {
        extensions.add(P10RequestGenerator.createExtensionSubjectInfoAccess(subjectInfoAccesses, false));
        needExtensionTypes.add(Extension.subjectInfoAccess.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)) {
        Set<ASN1ObjectIdentifier> oids = new HashSet<>(SecurityUtil.textToASN1ObjectIdentifers(extkeyusages));
        ExtendedKeyUsage extValue = X509Util.createExtendedUsage(oids);
        ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
        ExtensionExistence ee = new ExtensionExistence(
                SecurityUtil.textToASN1ObjectIdentifers(needExtensionTypes),
                SecurityUtil.textToASN1ObjectIdentifers(wantExtensionTypes));
        extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false,
                ee.toASN1Primitive().getEncoded()));
    }

    ConcurrentContentSigner identifiedSigner = getSigner(hashAlgo, new SignatureAlgoControl(rsaMgf1, dsaPlain));
    Certificate cert = Certificate.getInstance(identifiedSigner.getCertificate().getEncoded());

    X500Name subjectDN;
    if (subject != null) {
        subjectDN = new X500Name(subject);
    } else {
        subjectDN = cert.getSubject();
    }

    SubjectPublicKeyInfo subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();

    ContentSigner signer = identifiedSigner.borrowContentSigner();

    PKCS10CertificationRequest p10Req;
    try {
        p10Req = p10Gen.generateRequest(signer, subjectPublicKeyInfo, subjectDN, extensions);
    } finally {
        identifiedSigner.returnContentSigner(signer);
    }

    File file = new File(outputFilename);
    saveVerbose("saved PKCS#10 request to file", file, p10Req.getEncoded());
    return null;
}