Search in sources :

Example 76 with ASN1Encodable

use of com.android.org.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.

the class CaCertStoreDbImporter method importEntries.

private long importEntries(CaDbEntryType type, String entriesZipFile, long minId, File processLogFile, ProcessLog processLog, int numProcessedInLastProcess, PreparedStatement[] statements, String[] sqls) throws Exception {
    final int numEntriesPerCommit = Math.max(1, Math.round(type.getSqlBatchFactor() * numCertsPerCommit));
    ZipFile zipFile = new ZipFile(new File(entriesZipFile));
    ZipEntry entriesXmlEntry = zipFile.getEntry("overview.xml");
    DbiXmlReader entries;
    try {
        entries = createReader(type, zipFile.getInputStream(entriesXmlEntry));
    } catch (Exception ex) {
        try {
            zipFile.close();
        } catch (Exception e2) {
            LOG.error("could not close ZIP file {}: {}", entriesZipFile, e2.getMessage());
            LOG.debug("could not close ZIP file " + entriesZipFile, e2);
        }
        throw ex;
    }
    disableAutoCommit();
    try {
        int numEntriesInBatch = 0;
        long lastSuccessfulEntryId = 0;
        while (entries.hasNext()) {
            if (stopMe.get()) {
                throw new InterruptedException("interrupted by the user");
            }
            IdentifidDbObjectType entry = (IdentifidDbObjectType) entries.next();
            long id = entry.getId();
            if (id < minId) {
                continue;
            }
            numEntriesInBatch++;
            if (CaDbEntryType.CERT == type) {
                CertType cert = (CertType) entry;
                int certArt = (cert.getArt() == null) ? 1 : cert.getArt();
                String filename = cert.getFile();
                // rawcert
                ZipEntry certZipEnty = zipFile.getEntry(filename);
                // rawcert
                byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty));
                TBSCertificate tbsCert;
                try {
                    Certificate cc = Certificate.getInstance(encodedCert);
                    tbsCert = cc.getTBSCertificate();
                } catch (RuntimeException ex) {
                    LOG.error("could not parse certificate in file {}", filename);
                    LOG.debug("could not parse certificate in file " + filename, ex);
                    throw new CertificateException(ex.getMessage(), ex);
                }
                byte[] encodedKey = tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
                String b64Sha1FpCert = HashAlgo.SHA1.base64Hash(encodedCert);
                // cert
                String subjectText = X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen);
                PreparedStatement psCert = statements[0];
                PreparedStatement psRawcert = statements[1];
                try {
                    int idx = 1;
                    psCert.setLong(idx++, id);
                    psCert.setInt(idx++, certArt);
                    psCert.setLong(idx++, cert.getUpdate());
                    psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16));
                    psCert.setString(idx++, subjectText);
                    long fpSubject = X509Util.fpCanonicalizedName(tbsCert.getSubject());
                    psCert.setLong(idx++, fpSubject);
                    if (cert.getFpRs() != null) {
                        psCert.setLong(idx++, cert.getFpRs());
                    } else {
                        psCert.setNull(idx++, Types.BIGINT);
                    }
                    psCert.setLong(idx++, tbsCert.getStartDate().getDate().getTime() / 1000);
                    psCert.setLong(idx++, tbsCert.getEndDate().getDate().getTime() / 1000);
                    setBoolean(psCert, idx++, cert.getRev());
                    setInt(psCert, idx++, cert.getRr());
                    setLong(psCert, idx++, cert.getRt());
                    setLong(psCert, idx++, cert.getRit());
                    setInt(psCert, idx++, cert.getPid());
                    setInt(psCert, idx++, cert.getCaId());
                    setInt(psCert, idx++, cert.getRid());
                    setInt(psCert, idx++, cert.getUid());
                    psCert.setLong(idx++, FpIdCalculator.hash(encodedKey));
                    Extension extension = tbsCert.getExtensions().getExtension(Extension.basicConstraints);
                    boolean ee = true;
                    if (extension != null) {
                        ASN1Encodable asn1 = extension.getParsedValue();
                        ee = !BasicConstraints.getInstance(asn1).isCA();
                    }
                    psCert.setInt(idx++, ee ? 1 : 0);
                    psCert.setInt(idx++, cert.getReqType());
                    String tidS = null;
                    if (cert.getTid() != null) {
                        tidS = cert.getTid();
                    }
                    psCert.setString(idx++, tidS);
                    psCert.addBatch();
                } catch (SQLException ex) {
                    throw translate(SQL_ADD_CERT, ex);
                }
                try {
                    int idx = 1;
                    psRawcert.setLong(idx++, cert.getId());
                    psRawcert.setString(idx++, b64Sha1FpCert);
                    psRawcert.setString(idx++, cert.getRs());
                    psRawcert.setString(idx++, Base64.encodeToString(encodedCert));
                    psRawcert.addBatch();
                } catch (SQLException ex) {
                    throw translate(SQL_ADD_CRAW, ex);
                }
            } else if (CaDbEntryType.CRL == type) {
                PreparedStatement psAddCrl = statements[0];
                CrlType crl = (CrlType) entry;
                String filename = crl.getFile();
                // CRL
                ZipEntry zipEnty = zipFile.getEntry(filename);
                // rawcert
                byte[] encodedCrl = IoUtil.read(zipFile.getInputStream(zipEnty));
                X509CRL x509crl = null;
                try {
                    x509crl = X509Util.parseCrl(encodedCrl);
                } catch (Exception ex) {
                    LOG.error("could not parse CRL in file {}", filename);
                    LOG.debug("could not parse CRL in file " + filename, ex);
                    if (ex instanceof CRLException) {
                        throw (CRLException) ex;
                    } else {
                        throw new CRLException(ex.getMessage(), ex);
                    }
                }
                try {
                    byte[] octetString = x509crl.getExtensionValue(Extension.cRLNumber.getId());
                    if (octetString == null) {
                        LOG.warn("CRL without CRL number, ignore it");
                        continue;
                    }
                    byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
                    // CHECKSTYLE:SKIP
                    BigInteger crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
                    BigInteger baseCrlNumber = null;
                    octetString = x509crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
                    if (octetString != null) {
                        extnValue = DEROctetString.getInstance(octetString).getOctets();
                        baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
                    }
                    int idx = 1;
                    psAddCrl.setLong(idx++, crl.getId());
                    psAddCrl.setInt(idx++, crl.getCaId());
                    psAddCrl.setLong(idx++, crlNumber.longValue());
                    psAddCrl.setLong(idx++, x509crl.getThisUpdate().getTime() / 1000);
                    if (x509crl.getNextUpdate() != null) {
                        psAddCrl.setLong(idx++, x509crl.getNextUpdate().getTime() / 1000);
                    } else {
                        psAddCrl.setNull(idx++, Types.INTEGER);
                    }
                    if (baseCrlNumber == null) {
                        setBoolean(psAddCrl, idx++, false);
                        psAddCrl.setNull(idx++, Types.BIGINT);
                    } else {
                        setBoolean(psAddCrl, idx++, true);
                        psAddCrl.setLong(idx++, baseCrlNumber.longValue());
                    }
                    String str = Base64.encodeToString(encodedCrl);
                    psAddCrl.setString(idx++, str);
                    psAddCrl.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import CRL with ID=" + crl.getId() + ", message: " + ex.getMessage());
                    throw ex;
                }
            } else if (CaDbEntryType.REQUEST == type) {
                PreparedStatement psAddRequest = statements[0];
                RequestType request = (RequestType) entry;
                String filename = request.getFile();
                ZipEntry zipEnty = zipFile.getEntry(filename);
                byte[] encodedRequest = IoUtil.read(zipFile.getInputStream(zipEnty));
                try {
                    int idx = 1;
                    psAddRequest.setLong(idx++, request.getId());
                    psAddRequest.setLong(idx++, request.getUpdate());
                    psAddRequest.setString(idx++, Base64.encodeToString(encodedRequest));
                    psAddRequest.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import REQUEST with ID=" + request.getId() + ", message: " + ex.getMessage());
                    throw ex;
                }
            } else if (CaDbEntryType.REQCERT == type) {
                PreparedStatement psAddReqCert = statements[0];
                RequestCertType reqCert = (RequestCertType) entry;
                try {
                    int idx = 1;
                    psAddReqCert.setLong(idx++, reqCert.getId());
                    psAddReqCert.setLong(idx++, reqCert.getRid());
                    psAddReqCert.setLong(idx++, reqCert.getCid());
                    psAddReqCert.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import REQUEST with ID=" + reqCert.getId() + ", message: " + ex.getMessage());
                    throw ex;
                }
            } else {
                throw new RuntimeException("Unknown CaDbEntryType " + type);
            }
            boolean isLastBlock = !entries.hasNext();
            if (numEntriesInBatch > 0 && (numEntriesInBatch % numEntriesPerCommit == 0 || isLastBlock)) {
                if (evaulateOnly) {
                    for (PreparedStatement m : statements) {
                        m.clearBatch();
                    }
                } else {
                    String sql = null;
                    try {
                        for (int i = 0; i < sqls.length; i++) {
                            sql = sqls[i];
                            statements[i].executeBatch();
                        }
                        sql = null;
                        commit("(commit import to CA)");
                    } catch (Throwable th) {
                        rollback();
                        deleteFromTableWithLargerId(type.getTableName(), "ID", id, LOG);
                        if (CaDbEntryType.CERT == type) {
                            deleteFromTableWithLargerId("CRAW", "CID", id, LOG);
                        }
                        if (th instanceof SQLException) {
                            throw translate(sql, (SQLException) th);
                        } else if (th instanceof Exception) {
                            throw (Exception) th;
                        } else {
                            throw new Exception(th);
                        }
                    }
                }
                lastSuccessfulEntryId = id;
                processLog.addNumProcessed(numEntriesInBatch);
                numEntriesInBatch = 0;
                echoToFile(type + ":" + (numProcessedInLastProcess + processLog.numProcessed()) + ":" + lastSuccessfulEntryId, processLogFile);
                processLog.printStatus();
            }
        }
        return lastSuccessfulEntryId;
    } finally {
        recoverAutoCommit();
        zipFile.close();
    }
}
Also used : X509CRL(java.security.cert.X509CRL) SQLException(java.sql.SQLException) ZipEntry(java.util.zip.ZipEntry) RequestCertType(org.xipki.ca.dbtool.xmlio.ca.RequestCertType) CertType(org.xipki.ca.dbtool.xmlio.ca.CertType) CertificateException(java.security.cert.CertificateException) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) CRLException(java.security.cert.CRLException) IdentifidDbObjectType(org.xipki.ca.dbtool.xmlio.IdentifidDbObjectType) DbiXmlReader(org.xipki.ca.dbtool.xmlio.DbiXmlReader) PreparedStatement(java.sql.PreparedStatement) RequestCertType(org.xipki.ca.dbtool.xmlio.ca.RequestCertType) XMLStreamException(javax.xml.stream.XMLStreamException) DataAccessException(org.xipki.datasource.DataAccessException) JAXBException(javax.xml.bind.JAXBException) InvalidDataObjectException(org.xipki.ca.dbtool.xmlio.InvalidDataObjectException) CRLException(java.security.cert.CRLException) SQLException(java.sql.SQLException) CertificateException(java.security.cert.CertificateException) Extension(org.bouncycastle.asn1.x509.Extension) ZipFile(java.util.zip.ZipFile) CrlType(org.xipki.ca.dbtool.xmlio.ca.CrlType) BigInteger(java.math.BigInteger) ZipFile(java.util.zip.ZipFile) File(java.io.File) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) RequestType(org.xipki.ca.dbtool.xmlio.ca.RequestType)

Example 77 with ASN1Encodable

use of com.android.org.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.

the class X509CertprofileUtil method createGeneralName.

/**
 * Creates GeneralName.
 *
 * @param requestedName
 *          Requested name. Must not be {@code null}.
 * @param modes
 *          Modes to be considered. Must not be {@code null}.
 * @return the created GeneralName
 * @throws BadCertTemplateException
 *         If requestedName is invalid or contains entries which are not allowed in the modes.
 */
public static GeneralName createGeneralName(GeneralName requestedName, Set<GeneralNameMode> modes) throws BadCertTemplateException {
    ParamUtil.requireNonNull("requestedName", requestedName);
    int tag = requestedName.getTagNo();
    GeneralNameMode mode = null;
    if (modes != null) {
        for (GeneralNameMode m : modes) {
            if (m.getTag().getTag() == tag) {
                mode = m;
                break;
            }
        }
        if (mode == null) {
            throw new BadCertTemplateException("generalName tag " + tag + " is not allowed");
        }
    }
    switch(tag) {
        case GeneralName.rfc822Name:
        case GeneralName.dNSName:
        case GeneralName.uniformResourceIdentifier:
        case GeneralName.iPAddress:
        case GeneralName.registeredID:
        case GeneralName.directoryName:
            return new GeneralName(tag, requestedName.getName());
        case GeneralName.otherName:
            ASN1Sequence reqSeq = ASN1Sequence.getInstance(requestedName.getName());
            int size = reqSeq.size();
            if (size != 2) {
                throw new BadCertTemplateException("invalid otherName sequence: size is not 2: " + size);
            }
            ASN1ObjectIdentifier type = ASN1ObjectIdentifier.getInstance(reqSeq.getObjectAt(0));
            if (mode != null && !mode.getAllowedTypes().contains(type)) {
                throw new BadCertTemplateException("otherName.type " + type.getId() + " is not allowed");
            }
            ASN1Encodable asn1 = reqSeq.getObjectAt(1);
            if (!(asn1 instanceof ASN1TaggedObject)) {
                throw new BadCertTemplateException("otherName.value is not tagged Object");
            }
            int tagNo = ASN1TaggedObject.getInstance(asn1).getTagNo();
            if (tagNo != 0) {
                throw new BadCertTemplateException("otherName.value does not have tag 0: " + tagNo);
            }
            ASN1EncodableVector vector = new ASN1EncodableVector();
            vector.add(type);
            vector.add(new DERTaggedObject(true, 0, ASN1TaggedObject.getInstance(asn1).getObject()));
            DERSequence seq = new DERSequence(vector);
            return new GeneralName(GeneralName.otherName, seq);
        case GeneralName.ediPartyName:
            reqSeq = ASN1Sequence.getInstance(requestedName.getName());
            size = reqSeq.size();
            String nameAssigner = null;
            int idx = 0;
            if (size > 1) {
                DirectoryString ds = DirectoryString.getInstance(ASN1TaggedObject.getInstance(reqSeq.getObjectAt(idx++)).getObject());
                nameAssigner = ds.getString();
            }
            DirectoryString ds = DirectoryString.getInstance(ASN1TaggedObject.getInstance(reqSeq.getObjectAt(idx++)).getObject());
            String partyName = ds.getString();
            vector = new ASN1EncodableVector();
            if (nameAssigner != null) {
                vector.add(new DERTaggedObject(false, 0, new DirectoryString(nameAssigner)));
            }
            vector.add(new DERTaggedObject(false, 1, new DirectoryString(partyName)));
            seq = new DERSequence(vector);
            return new GeneralName(GeneralName.ediPartyName, seq);
        default:
            throw new RuntimeException("should not reach here, unknown GeneralName tag " + tag);
    }
// end switch (tag)
}
Also used : GeneralNameMode(org.xipki.ca.api.profile.GeneralNameMode) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERSequence(org.bouncycastle.asn1.DERSequence) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 78 with ASN1Encodable

use of com.android.org.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.

the class ProxyP11Module method refresh.

public void refresh() throws P11TokenException {
    byte[] resp = send(P11ProxyConstants.ACTION_GET_SERVER_CAPS, null);
    Asn1ServerCaps caps;
    try {
        caps = Asn1ServerCaps.getInstance(resp);
    } catch (BadAsn1ObjectException ex) {
        throw new P11TokenException("response is a valid Asn1ServerCaps", ex);
    }
    if (!caps.getVersions().contains(version)) {
        throw new P11TokenException("Server does not support any version supported by the client");
    }
    this.readOnly = caps.isReadOnly();
    resp = send(P11ProxyConstants.ACTION_GET_SLOT_IDS, null);
    ASN1Sequence seq;
    try {
        seq = ASN1Sequence.getInstance(resp);
    } catch (IllegalArgumentException ex) {
        throw new P11TokenException("response is not ASN1Sequence", ex);
    }
    final int n = seq.size();
    Set<P11Slot> slots = new HashSet<>();
    for (int i = 0; i < n; i++) {
        Asn1P11SlotIdentifier asn1SlotId;
        try {
            ASN1Encodable obj = seq.getObjectAt(i);
            asn1SlotId = Asn1P11SlotIdentifier.getInstance(obj);
        } catch (Exception ex) {
            throw new P11TokenException(ex.getMessage(), ex);
        }
        P11SlotIdentifier slotId = asn1SlotId.getSlotId();
        if (!conf.isSlotIncluded(slotId)) {
            continue;
        }
        if (!conf.isSlotIncluded(slotId)) {
            LOG.info("skipped slot {}", slotId);
            continue;
        }
        P11Slot slot = new ProxyP11Slot(this, slotId, conf.isReadOnly(), conf.getP11MechanismFilter());
        slots.add(slot);
    }
    setSlots(slots);
}
Also used : Asn1ServerCaps(org.xipki.p11proxy.msg.Asn1ServerCaps) Asn1P11SlotIdentifier(org.xipki.p11proxy.msg.Asn1P11SlotIdentifier) P11SlotIdentifier(org.xipki.security.pkcs11.P11SlotIdentifier) P11TokenException(org.xipki.security.exception.P11TokenException) P11Slot(org.xipki.security.pkcs11.P11Slot) P11TokenException(org.xipki.security.exception.P11TokenException) BadAsn1ObjectException(org.xipki.security.exception.BadAsn1ObjectException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) BadAsn1ObjectException(org.xipki.security.exception.BadAsn1ObjectException) HashSet(java.util.HashSet) Asn1P11SlotIdentifier(org.xipki.p11proxy.msg.Asn1P11SlotIdentifier)

Example 79 with ASN1Encodable

use of com.android.org.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.

the class OcspStatusCmd method processResponse.

@Override
protected Object processResponse(OCSPResp response, X509Certificate respIssuer, IssuerHash issuerHash, List<BigInteger> serialNumbers, Map<BigInteger, byte[]> encodedCerts) throws Exception {
    ParamUtil.requireNonNull("response", response);
    ParamUtil.requireNonNull("issuerHash", issuerHash);
    ParamUtil.requireNonNull("serialNumbers", serialNumbers);
    BasicOCSPResp basicResp = OcspUtils.extractBasicOcspResp(response);
    boolean extendedRevoke = basicResp.getExtension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke) != null;
    SingleResp[] singleResponses = basicResp.getResponses();
    if (singleResponses == null || singleResponses.length == 0) {
        throw new CmdFailure("received no status from server");
    }
    final int n = singleResponses.length;
    if (n != serialNumbers.size()) {
        throw new CmdFailure("received status with " + n + " single responses from server, but " + serialNumbers.size() + " were requested");
    }
    Date[] thisUpdates = new Date[n];
    for (int i = 0; i < n; i++) {
        thisUpdates[i] = singleResponses[i].getThisUpdate();
    }
    // check the signature if available
    if (null == basicResp.getSignature()) {
        println("response is not signed");
    } else {
        X509CertificateHolder[] responderCerts = basicResp.getCerts();
        if (responderCerts == null || responderCerts.length < 1) {
            throw new CmdFailure("no responder certificate is contained in the response");
        }
        ResponderID respId = basicResp.getResponderId().toASN1Primitive();
        X500Name respIdByName = respId.getName();
        byte[] respIdByKey = respId.getKeyHash();
        X509CertificateHolder respSigner = null;
        for (X509CertificateHolder cert : responderCerts) {
            if (respIdByName != null) {
                if (cert.getSubject().equals(respIdByName)) {
                    respSigner = cert;
                }
            } else {
                byte[] spkiSha1 = HashAlgo.SHA1.hash(cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
                if (Arrays.equals(respIdByKey, spkiSha1)) {
                    respSigner = cert;
                }
            }
            if (respSigner != null) {
                break;
            }
        }
        if (respSigner == null) {
            throw new CmdFailure("no responder certificate match the ResponderId");
        }
        boolean validOn = true;
        for (Date thisUpdate : thisUpdates) {
            validOn = respSigner.isValidOn(thisUpdate);
            if (!validOn) {
                throw new CmdFailure("responder certificate is not valid on " + thisUpdate);
            }
        }
        if (validOn) {
            PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
            ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(responderPubKey);
            boolean sigValid = basicResp.isSignatureValid(cvp);
            if (!sigValid) {
                throw new CmdFailure("response is equipped with invalid signature");
            }
            // verify the OCSPResponse signer
            if (respIssuer != null) {
                boolean certValid = true;
                X509Certificate jceRespSigner = X509Util.toX509Cert(respSigner.toASN1Structure());
                if (X509Util.issues(respIssuer, jceRespSigner)) {
                    try {
                        jceRespSigner.verify(respIssuer.getPublicKey());
                    } catch (SignatureException ex) {
                        certValid = false;
                    }
                }
                if (!certValid) {
                    throw new CmdFailure("response is equipped with valid signature but the" + " OCSP signer is not trusted");
                }
            } else {
                println("response is equipped with valid signature");
            }
        // end if(respIssuer)
        }
        if (verbose.booleanValue()) {
            println("responder is " + X509Util.getRfc4519Name(responderCerts[0].getSubject()));
        }
    }
    for (int i = 0; i < n; i++) {
        if (n > 1) {
            println("---------------------------- " + i + "----------------------------");
        }
        SingleResp singleResp = singleResponses[i];
        CertificateStatus singleCertStatus = singleResp.getCertStatus();
        String status;
        if (singleCertStatus == null) {
            status = "good";
        } else if (singleCertStatus instanceof RevokedStatus) {
            RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
            Date revTime = revStatus.getRevocationTime();
            Date invTime = null;
            Extension ext = singleResp.getExtension(Extension.invalidityDate);
            if (ext != null) {
                invTime = ASN1GeneralizedTime.getInstance(ext.getParsedValue()).getDate();
            }
            if (revStatus.hasRevocationReason()) {
                int reason = revStatus.getRevocationReason();
                if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTime.getTime() == 0) {
                    status = "unknown (RFC6960)";
                } else {
                    status = StringUtil.concatObjects("revoked, reason = ", CrlReason.forReasonCode(reason).getDescription(), ", revocationTime = ", revTime, (invTime == null ? "" : ", invalidityTime = " + invTime));
                }
            } else {
                status = "revoked, no reason, revocationTime = " + revTime;
            }
        } else if (singleCertStatus instanceof UnknownStatus) {
            status = "unknown (RFC2560)";
        } else {
            status = "ERROR";
        }
        StringBuilder msg = new StringBuilder();
        CertificateID certId = singleResp.getCertID();
        HashAlgo hashAlgo = HashAlgo.getNonNullInstance(certId.getHashAlgOID());
        boolean issuerMatch = issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash());
        BigInteger serialNumber = certId.getSerialNumber();
        msg.append("issuer matched: ").append(issuerMatch);
        msg.append("\nserialNumber: ").append(LogUtil.formatCsn(serialNumber));
        msg.append("\nCertificate status: ").append(status);
        if (verbose.booleanValue()) {
            msg.append("\nthisUpdate: ").append(singleResp.getThisUpdate());
            msg.append("\nnextUpdate: ").append(singleResp.getNextUpdate());
            Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
            if (extension != null) {
                msg.append("\nCertHash is provided:\n");
                ASN1Encodable extensionValue = extension.getParsedValue();
                CertHash certHash = CertHash.getInstance(extensionValue);
                ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
                byte[] hashValue = certHash.getCertificateHash();
                msg.append("\tHash algo : ").append(hashAlgOid.getId()).append("\n");
                msg.append("\tHash value: ").append(Hex.encode(hashValue)).append("\n");
                if (encodedCerts != null) {
                    byte[] encodedCert = encodedCerts.get(serialNumber);
                    MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
                    byte[] expectedHashValue = md.digest(encodedCert);
                    if (Arrays.equals(expectedHashValue, hashValue)) {
                        msg.append("\tThis matches the requested certificate");
                    } else {
                        msg.append("\tThis differs from the requested certificate");
                    }
                }
            }
            // end if (extension != null)
            extension = singleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
            if (extension != null) {
                ASN1Encodable extensionValue = extension.getParsedValue();
                ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(extensionValue);
                msg.append("\nArchive-CutOff: ");
                msg.append(time.getTimeString());
            }
            AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
            if (sigAlg == null) {
                msg.append(("\nresponse is not signed"));
            } else {
                String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
                if (sigAlgName == null) {
                    sigAlgName = "unknown";
                }
                msg.append("\nresponse is signed with ").append(sigAlgName);
            }
            // extensions
            msg.append("\nExtensions: ");
            List<?> extensionOids = basicResp.getExtensionOIDs();
            if (extensionOids == null || extensionOids.size() == 0) {
                msg.append("-");
            } else {
                int size = extensionOids.size();
                for (int j = 0; j < size; j++) {
                    ASN1ObjectIdentifier extensionOid = (ASN1ObjectIdentifier) extensionOids.get(j);
                    String name = EXTENSION_OIDNAME_MAP.get(extensionOid);
                    if (name == null) {
                        msg.append(extensionOid.getId());
                    } else {
                        msg.append(name);
                    }
                    if (j != size - 1) {
                        msg.append(", ");
                    }
                }
            }
        }
        // end if (verbose.booleanValue())
        println(msg.toString());
    }
    // end for
    println("");
    return null;
}
Also used : HashAlgo(org.xipki.security.HashAlgo) ResponderID(org.bouncycastle.asn1.ocsp.ResponderID) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) X500Name(org.bouncycastle.asn1.x500.X500Name) SignatureException(java.security.SignatureException) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) CmdFailure(org.xipki.console.karaf.CmdFailure) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) MessageDigest(java.security.MessageDigest) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) CertHash(org.bouncycastle.asn1.isismtt.ocsp.CertHash) PublicKey(java.security.PublicKey) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Extension(org.bouncycastle.asn1.x509.Extension) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 80 with ASN1Encodable

use of com.android.org.bouncycastle.asn1.ASN1Encodable in project signer by demoiselle.

the class RevocationRefs method getValue.

@Override
public Attribute getValue() throws SignerException {
    try {
        int chainSize = certificates.length - 1;
        ArrayList<CrlValidatedID> crls = new ArrayList<CrlValidatedID>();
        for (int ix = 0; ix < chainSize; ix++) {
            X509Certificate cert = (X509Certificate) certificates[ix];
            Collection<ICPBR_CRL> icpCrls = crlRepository.getX509CRL(cert);
            for (ICPBR_CRL icpCrl : icpCrls) {
                crls.add(makeCrlValidatedID(icpCrl.getCRL()));
            }
        }
        int crlsIdSize = crls.size();
        CrlValidatedID[] crlsForId = new CrlValidatedID[crlsIdSize];
        int i = 0;
        for (CrlValidatedID crlVID : crls) {
            crlsForId[i] = crlVID;
            i++;
        }
        // CrlListID crlids = new CrlListID(crlsForId);
        DERSequence crlValidatedIDSeq = new DERSequence(crlsForId);
        // --CRLListID--/
        ASN1Encodable[] crlValidatedIDSeqArr = new ASN1Encodable[1];
        crlValidatedIDSeqArr[0] = crlValidatedIDSeq;
        DERSequence crlListID = new DERSequence(crlValidatedIDSeqArr);
        // CRLListID--/
        DERTaggedObject crlListIDTagged = new DERTaggedObject(0, crlListID);
        // CrlOcspRef--/
        ASN1Encodable[] crlListIDTaggedArr = new ASN1Encodable[1];
        crlListIDTaggedArr[0] = crlListIDTagged;
        DERSequence crlOscpRef = new DERSequence(crlListIDTaggedArr);
        // --CompleteRevocationRefs--/
        ASN1Encodable[] crlOscpRefArr = new ASN1Encodable[1];
        crlOscpRefArr[0] = crlOscpRef;
        DERSequence completeRevocationRefs = new DERSequence(crlOscpRefArr);
        // CrlOcspRef crlOcspRef = new CrlOcspRef(crlids, null, null);
        return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(completeRevocationRefs));
    // CrlOcspRef[] crlOcspRefArray = new
    // CrlOcspRef[completeRevocationRefs.size()];
    } catch (NoSuchAlgorithmException | CRLException e) {
        throw new SignerException(e.getMessage());
    }
}
Also used : Attribute(org.bouncycastle.asn1.cms.Attribute) UnsignedAttribute(org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.UnsignedAttribute) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ArrayList(java.util.ArrayList) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DERSet(org.bouncycastle.asn1.DERSet) X509Certificate(java.security.cert.X509Certificate) ICPBR_CRL(org.demoiselle.signer.core.extension.ICPBR_CRL) CrlValidatedID(org.bouncycastle.asn1.esf.CrlValidatedID) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) CRLException(java.security.cert.CRLException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)139 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)73 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)59 IOException (java.io.IOException)37 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)34 DEROctetString (org.bouncycastle.asn1.DEROctetString)32 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)29 DERIA5String (org.bouncycastle.asn1.DERIA5String)28 DERSequence (org.bouncycastle.asn1.DERSequence)25 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)21 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)21 ArrayList (java.util.ArrayList)20 GeneralName (org.bouncycastle.asn1.x509.GeneralName)19 X509Certificate (java.security.cert.X509Certificate)17 HashSet (java.util.HashSet)17 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)17 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)17 BigInteger (java.math.BigInteger)16 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)16 DERBMPString (org.bouncycastle.asn1.DERBMPString)15