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

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

Introduction

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

Prototype

public SubjectPublicKeyInfo getSubjectPublicKeyInfo() 

Source Link

Usage

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  w  w.  j ava 2  s.  co 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  w  w.j  a  v a  2  s.co  m
        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  av a  2  s . 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.pki.ca.qa.ExtensionsChecker.java

License:Open Source License

public List<ValidationIssue> checkExtensions(final Certificate cert, final X509IssuerInfo issuerInfo,
        final Extensions requestedExtensions, final X500Name requestedSubject) {
    ParamUtil.requireNonNull("cert", cert);
    ParamUtil.requireNonNull("issuerInfo", issuerInfo);

    X509Certificate jceCert;//w w  w  .j a v  a2  s .  c om
    try {
        jceCert = X509Util.toX509Cert(cert);
    } catch (CertificateException ex) {
        throw new IllegalArgumentException("invalid cert: " + ex.getMessage());
    }

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

    // detect the list of extension types in certificate
    Set<ASN1ObjectIdentifier> presentExtenionTypes = getExensionTypes(cert, issuerInfo, requestedExtensions);

    Extensions extensions = cert.getTBSCertificate().getExtensions();
    ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs();

    if (oids == null) {
        ValidationIssue issue = new ValidationIssue("X509.EXT.GEN", "extension general");
        result.add(issue);
        issue.setFailureMessage("no extension is present");
        return result;
    }

    List<ASN1ObjectIdentifier> certExtTypes = Arrays.asList(oids);

    for (ASN1ObjectIdentifier extType : presentExtenionTypes) {
        if (!certExtTypes.contains(extType)) {
            ValidationIssue issue = createExtensionIssue(extType);
            result.add(issue);
            issue.setFailureMessage("extension is absent but is required");
        }
    }

    Map<ASN1ObjectIdentifier, ExtensionControl> extensionControls = certProfile.getExtensionControls();
    for (ASN1ObjectIdentifier oid : certExtTypes) {
        ValidationIssue issue = createExtensionIssue(oid);
        result.add(issue);
        if (!presentExtenionTypes.contains(oid)) {
            issue.setFailureMessage("extension is present but is not permitted");
            continue;
        }

        Extension ext = extensions.getExtension(oid);
        StringBuilder failureMsg = new StringBuilder();
        ExtensionControl extControl = extensionControls.get(oid);

        if (extControl.isCritical() != ext.isCritical()) {
            addViolation(failureMsg, "critical", ext.isCritical(), extControl.isCritical());
        }

        byte[] extensionValue = ext.getExtnValue().getOctets();
        try {
            if (Extension.authorityKeyIdentifier.equals(oid)) {
                // AuthorityKeyIdentifier
                checkExtensionIssuerKeyIdentifier(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.subjectKeyIdentifier.equals(oid)) {
                // SubjectKeyIdentifier
                checkExtensionSubjectKeyIdentifier(failureMsg, extensionValue, cert.getSubjectPublicKeyInfo());
            } else if (Extension.keyUsage.equals(oid)) {
                // KeyUsage
                checkExtensionKeyUsage(failureMsg, extensionValue, jceCert.getKeyUsage(), requestedExtensions,
                        extControl);
            } else if (Extension.certificatePolicies.equals(oid)) {
                // CertificatePolicies
                checkExtensionCertificatePolicies(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.policyMappings.equals(oid)) {
                // Policy Mappings
                checkExtensionPolicyMappings(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.subjectAlternativeName.equals(oid)) {
                // SubjectAltName
                checkExtensionSubjectAltName(failureMsg, extensionValue, requestedExtensions, extControl,
                        requestedSubject);
            } else if (Extension.subjectDirectoryAttributes.equals(oid)) {
                // SubjectDirectoryAttributes
                checkExtensionSubjectDirAttrs(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.issuerAlternativeName.equals(oid)) {
                // IssuerAltName
                checkExtensionIssuerAltNames(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.basicConstraints.equals(oid)) {
                // Basic Constraints
                checkExtensionBasicConstraints(failureMsg, extensionValue);
            } else if (Extension.nameConstraints.equals(oid)) {
                // Name Constraints
                checkExtensionNameConstraints(failureMsg, extensionValue, extensions, extControl);
            } else if (Extension.policyConstraints.equals(oid)) {
                // PolicyConstrains
                checkExtensionPolicyConstraints(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.extendedKeyUsage.equals(oid)) {
                // ExtendedKeyUsage
                checkExtensionExtendedKeyUsage(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.cRLDistributionPoints.equals(oid)) {
                // CRL Distribution Points
                checkExtensionCrlDistributionPoints(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.inhibitAnyPolicy.equals(oid)) {
                // Inhibit anyPolicy
                checkExtensionInhibitAnyPolicy(failureMsg, extensionValue, extensions, extControl);
            } else if (Extension.freshestCRL.equals(oid)) {
                // Freshest CRL
                checkExtensionDeltaCrlDistributionPoints(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.authorityInfoAccess.equals(oid)) {
                // Authority Information Access
                checkExtensionAuthorityInfoAccess(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.subjectInfoAccess.equals(oid)) {
                // SubjectInfoAccess
                checkExtensionSubjectInfoAccess(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_extension_admission.equals(oid)) {
                // Admission
                checkExtensionAdmission(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_extension_pkix_ocsp_nocheck.equals(oid)) {
                // ocsp-nocheck
                checkExtensionOcspNocheck(failureMsg, extensionValue);
            } else if (ObjectIdentifiers.id_extension_restriction.equals(oid)) {
                // restriction
                checkExtensionRestriction(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_extension_additionalInformation.equals(oid)) {
                // additionalInformation
                checkExtensionAdditionalInformation(failureMsg, extensionValue, requestedExtensions,
                        extControl);
            } else if (ObjectIdentifiers.id_extension_validityModel.equals(oid)) {
                // validityModel
                checkExtensionValidityModel(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.privateKeyUsagePeriod.equals(oid)) {
                // privateKeyUsagePeriod
                checkExtensionPrivateKeyUsagePeriod(failureMsg, extensionValue, jceCert.getNotBefore(),
                        jceCert.getNotAfter());
            } else if (Extension.qCStatements.equals(oid)) {
                // qCStatements
                checkExtensionQcStatements(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.biometricInfo.equals(oid)) {
                // biometricInfo
                checkExtensionBiometricInfo(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_pe_tlsfeature.equals(oid)) {
                // tlsFeature
                checkExtensionTlsFeature(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_xipki_ext_authorizationTemplate.equals(oid)) {
                // authorizationTemplate
                checkExtensionAuthorizationTemplate(failureMsg, extensionValue, requestedExtensions,
                        extControl);
            } else {
                byte[] expected;
                if (ObjectIdentifiers.id_smimeCapabilities.equals(oid)) {
                    // SMIMECapabilities
                    expected = smimeCapabilities.getValue();
                } else {
                    expected = getExpectedExtValue(oid, requestedExtensions, extControl);
                }

                if (!Arrays.equals(expected, extensionValue)) {
                    addViolation(failureMsg, "extension valus", hex(extensionValue),
                            (expected == null) ? "not present" : hex(expected));
                }
            }

            if (failureMsg.length() > 0) {
                issue.setFailureMessage(failureMsg.toString());
            }

        } catch (IllegalArgumentException | ClassCastException | ArrayIndexOutOfBoundsException ex) {
            LOG.debug("extension value does not have correct syntax", ex);
            issue.setFailureMessage("extension value does not have correct syntax");
        }
    }

    return result;
}

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 w  w w .j  av a 2 s .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.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  a v a 2s  . c o 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.server.impl.store.crl.CrlCertStatusStore.java

License:Open Source License

private synchronized void initializeStore(final boolean force) {
    Boolean updateCrlSuccessful = null;

    try {//  www  .  ja  va2 s. 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.db.DbCertStatusStore.java

License:Open Source License

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

    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;
}