Search in sources :

Example 81 with Time

use of org.bouncycastle.asn1.x509.Time 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 82 with Time

use of org.bouncycastle.asn1.x509.Time in project Etar-Calendar by Etar-Group.

the class SimpleWeekView method onHoverEvent.

@Override
public boolean onHoverEvent(MotionEvent event) {
    Context context = getContext();
    // only send accessibility events if accessibility and exploration are
    // on.
    AccessibilityManager am = (AccessibilityManager) context.getSystemService(Service.ACCESSIBILITY_SERVICE);
    if (!am.isEnabled() || !am.isTouchExplorationEnabled()) {
        return super.onHoverEvent(event);
    }
    if (event.getAction() != MotionEvent.ACTION_HOVER_EXIT) {
        Time hover = getDayFromLocation(event.getX());
        if (hover != null && (mLastHoverTime == null || hover.compareTo(mLastHoverTime) != 0)) {
            Long millis = hover.toMillis();
            String date = Utils.formatDateRange(context, millis, millis, DateUtils.FORMAT_SHOW_DATE);
            AccessibilityEvent accessEvent = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
            accessEvent.getText().add(date);
            sendAccessibilityEventUnchecked(accessEvent);
            mLastHoverTime = hover;
        }
    }
    return true;
}
Also used : Context(android.content.Context) AccessibilityManager(android.view.accessibility.AccessibilityManager) Time(com.android.calendarcommon2.Time) AccessibilityEvent(android.view.accessibility.AccessibilityEvent)

Example 83 with Time

use of org.bouncycastle.asn1.x509.Time in project Etar-Calendar by Etar-Group.

the class SimpleWeekView method setWeekParams.

/**
 * Sets all the parameters for displaying this week. The only required
 * parameter is the week number. Other parameters have a default value and
 * will only update if a new value is included, except for focus month,
 * which will always default to no focus month if no value is passed in. See
 * {@link #VIEW_PARAMS_HEIGHT} for more info on parameters.
 *
 * @param params A map of the new parameters, see
 *            {@link #VIEW_PARAMS_HEIGHT}
 * @param tz The time zone this view should reference times in
 */
public void setWeekParams(HashMap<String, Integer> params, String tz) {
    if (!params.containsKey(VIEW_PARAMS_WEEK)) {
        throw new InvalidParameterException("You must specify the week number for this view");
    }
    setTag(params);
    mTimeZone = tz;
    // We keep the current value for any params not present
    if (params.containsKey(VIEW_PARAMS_HEIGHT)) {
        mHeight = params.get(VIEW_PARAMS_HEIGHT);
        if (mHeight < MIN_HEIGHT) {
            mHeight = MIN_HEIGHT;
        }
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_DAY)) {
        mSelectedDay = params.get(VIEW_PARAMS_SELECTED_DAY);
    }
    mHasSelectedDay = mSelectedDay != -1;
    if (params.containsKey(VIEW_PARAMS_NUM_DAYS)) {
        mNumDays = params.get(VIEW_PARAMS_NUM_DAYS);
    }
    if (params.containsKey(VIEW_PARAMS_SHOW_WK_NUM)) {
        if (params.get(VIEW_PARAMS_SHOW_WK_NUM) != 0) {
            mShowWeekNum = true;
        } else {
            mShowWeekNum = false;
        }
    }
    mNumCells = mShowWeekNum ? mNumDays + 1 : mNumDays;
    // Allocate space for caching the day numbers and focus values
    mDayNumbers = new String[mNumCells];
    mFocusDay = new boolean[mNumCells];
    mOddMonth = new boolean[mNumCells];
    mWeek = params.get(VIEW_PARAMS_WEEK);
    int julianMonday = Utils.getJulianMondayFromWeeksSinceEpoch(mWeek);
    Time time = new Time(tz);
    time.setJulianDay(julianMonday);
    // If we're showing the week number calculate it based on Monday
    int i = 0;
    if (mShowWeekNum) {
        mDayNumbers[0] = NumberFormat.getInstance().format(time.getWeekNumber());
        i++;
    }
    if (params.containsKey(VIEW_PARAMS_WEEK_START)) {
        mWeekStart = params.get(VIEW_PARAMS_WEEK_START);
    }
    // Dec 27th 1969 -Jan 2nd, 1970
    if (time.getWeekDay() != mWeekStart) {
        int diff = time.getWeekDay() - mWeekStart;
        if (diff < 0) {
            diff += 7;
        }
        time.setDay(time.getDay() - diff);
        time.normalize();
    }
    mFirstJulianDay = Time.getJulianDay(time.toMillis(), time.getGmtOffset());
    mFirstMonth = time.getMonth();
    // Figure out what day today is
    Time today = new Time(tz);
    today.set(System.currentTimeMillis());
    mHasToday = false;
    mToday = -1;
    int focusMonth = params.containsKey(VIEW_PARAMS_FOCUS_MONTH) ? params.get(VIEW_PARAMS_FOCUS_MONTH) : DEFAULT_FOCUS_MONTH;
    for (; i < mNumCells; i++) {
        if (time.getDay() == 1) {
            mFirstMonth = time.getMonth();
        }
        mOddMonth[i] = (time.getMonth() % 2) == 1;
        if (time.getMonth() == focusMonth) {
            mFocusDay[i] = true;
        } else {
            mFocusDay[i] = false;
        }
        if (time.getYear() == today.getYear() && time.getYearDay() == today.getYearDay()) {
            mHasToday = true;
            mToday = i;
        }
        mDayNumbers[i] = NumberFormat.getInstance().format(time.getDay());
        time.setDay(time.getDay() + 1);
        time.normalize();
    }
    // new month undo it
    if (time.getDay() == 1) {
        time.setDay(time.getDay() - 1);
        time.normalize();
    }
    mLastMonth = time.getMonth();
    updateSelectionPositions();
}
Also used : InvalidParameterException(java.security.InvalidParameterException) Time(com.android.calendarcommon2.Time) Paint(android.graphics.Paint)

Example 84 with Time

use of org.bouncycastle.asn1.x509.Time in project Etar-Calendar by Etar-Group.

the class SimpleWeeksAdapter method onTouch.

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (mGestureDetector.onTouchEvent(event)) {
        SimpleWeekView view = (SimpleWeekView) v;
        Time day = ((SimpleWeekView) v).getDayFromLocation(event.getX());
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Touched day at Row=" + view.mWeek + " day=" + day.toString());
        }
        if (day != null) {
            onDayTapped(day);
        }
        return true;
    }
    return false;
}
Also used : Time(com.android.calendarcommon2.Time)

Example 85 with Time

use of org.bouncycastle.asn1.x509.Time in project Etar-Calendar by Etar-Group.

the class RecurrencePickerDialog method copyEventRecurrenceToModel.

// TODO don't lose data when getting data that our UI can't handle
private static void copyEventRecurrenceToModel(final EventRecurrence er, RecurrenceModel model) {
    // Freq:
    switch(er.freq) {
        case EventRecurrence.DAILY:
            model.freq = RecurrenceModel.FREQ_DAILY;
            break;
        case EventRecurrence.MONTHLY:
            model.freq = RecurrenceModel.FREQ_MONTHLY;
            break;
        case EventRecurrence.YEARLY:
            model.freq = RecurrenceModel.FREQ_YEARLY;
            break;
        case EventRecurrence.WEEKLY:
            model.freq = RecurrenceModel.FREQ_WEEKLY;
            break;
        default:
            throw new IllegalStateException("freq=" + er.freq);
    }
    // Interval:
    if (er.interval > 0) {
        model.interval = er.interval;
    }
    // End:
    // End by count:
    model.endCount = er.count;
    if (model.endCount > 0) {
        model.end = RecurrenceModel.END_BY_COUNT;
    }
    // End by date:
    if (!TextUtils.isEmpty(er.until)) {
        if (model.endDate == null) {
            model.endDate = new Time();
        }
        try {
            model.endDate.parse(er.until);
        } catch (TimeFormatException e) {
            model.endDate = null;
        }
        // LIMITATION: The UI can only handle END_BY_DATE or END_BY_COUNT
        if (model.end == RecurrenceModel.END_BY_COUNT && model.endDate != null) {
            throw new IllegalStateException("freq=" + er.freq);
        }
        model.end = RecurrenceModel.END_BY_DATE;
    }
    // Weekly: repeat by day of week or Monthly: repeat by nth day of week
    // in the month
    Arrays.fill(model.weeklyByDayOfWeek, false);
    if (er.bydayCount > 0) {
        int count = 0;
        for (int i = 0; i < er.bydayCount; i++) {
            int dayOfWeek = EventRecurrence.day2TimeDay(er.byday[i]);
            model.weeklyByDayOfWeek[dayOfWeek] = true;
            if (model.freq == RecurrenceModel.FREQ_MONTHLY && isSupportedMonthlyByNthDayOfWeek(er.bydayNum[i])) {
                // LIMITATION: Can handle only (one) weekDayNum in nth or last and only
                // when
                // monthly
                model.monthlyByDayOfWeek = dayOfWeek;
                model.monthlyByNthDayOfWeek = er.bydayNum[i];
                model.monthlyRepeat = RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK;
                count++;
            }
        }
        if (model.freq == RecurrenceModel.FREQ_MONTHLY) {
            if (er.bydayCount != 1) {
                // Can't handle 1st Monday and 2nd Wed
                throw new IllegalStateException("Can handle only 1 byDayOfWeek in monthly");
            }
            if (count != 1) {
                throw new IllegalStateException("Didn't specify which nth day of week to repeat for a monthly");
            }
        }
    }
    // Monthly by day of month
    if (model.freq == RecurrenceModel.FREQ_MONTHLY) {
        if (er.bymonthdayCount == 1) {
            if (model.monthlyRepeat == RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK) {
                throw new IllegalStateException("Can handle only by monthday or by nth day of week, not both");
            }
            model.monthlyByMonthDay = er.bymonthday[0];
            model.monthlyRepeat = RecurrenceModel.MONTHLY_BY_DATE;
        } else if (er.bymonthCount > 1) {
            // LIMITATION: Can handle only one month day
            throw new IllegalStateException("Can handle only one bymonthday");
        }
    }
}
Also used : Time(com.android.calendarcommon2.Time) TimeFormatException(android.util.TimeFormatException)

Aggregations

Time (com.android.calendarcommon2.Time)178 IOException (java.io.IOException)50 Date (java.util.Date)43 X509Certificate (java.security.cert.X509Certificate)37 BigInteger (java.math.BigInteger)32 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)32 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)32 X500Name (org.bouncycastle.asn1.x500.X500Name)28 DEROctetString (org.bouncycastle.asn1.DEROctetString)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)26 ArrayList (java.util.ArrayList)25 Paint (android.graphics.Paint)20 DERSequence (org.bouncycastle.asn1.DERSequence)17 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)16 ByteArrayInputStream (java.io.ByteArrayInputStream)15 CertificateException (java.security.cert.CertificateException)15 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)15 Time (org.bouncycastle.asn1.x509.Time)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 SecureRandom (java.security.SecureRandom)14