001: package org.bouncycastle.asn1.x509;
002:
003: import org.bouncycastle.asn1.ASN1Choice;
004: import org.bouncycastle.asn1.ASN1Encodable;
005: import org.bouncycastle.asn1.ASN1TaggedObject;
006: import org.bouncycastle.asn1.DERGeneralizedTime;
007: import org.bouncycastle.asn1.DERObject;
008: import org.bouncycastle.asn1.DERUTCTime;
009:
010: import java.text.ParseException;
011: import java.text.SimpleDateFormat;
012: import java.util.Date;
013: import java.util.SimpleTimeZone;
014:
015: public class Time extends ASN1Encodable implements ASN1Choice {
016: DERObject time;
017:
018: public static Time getInstance(ASN1TaggedObject obj,
019: boolean explicit) {
020: return getInstance(obj.getObject()); // must be explicitly tagged
021: }
022:
023: public Time(DERObject time) {
024: if (!(time instanceof DERUTCTime)
025: && !(time instanceof DERGeneralizedTime)) {
026: throw new IllegalArgumentException(
027: "unknown object passed to Time");
028: }
029:
030: this .time = time;
031: }
032:
033: /**
034: * creates a time object from a given date - if the date is between 1950
035: * and 2049 a UTCTime object is generated, otherwise a GeneralizedTime
036: * is used.
037: */
038: public Time(Date date) {
039: SimpleTimeZone tz = new SimpleTimeZone(0, "Z");
040: SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmss");
041:
042: dateF.setTimeZone(tz);
043:
044: String d = dateF.format(date) + "Z";
045: int year = Integer.parseInt(d.substring(0, 4));
046:
047: if (year < 1950 || year > 2049) {
048: time = new DERGeneralizedTime(d);
049: } else {
050: time = new DERUTCTime(d.substring(2));
051: }
052: }
053:
054: public static Time getInstance(Object obj) {
055: if (obj instanceof Time) {
056: return (Time) obj;
057: } else if (obj instanceof DERUTCTime) {
058: return new Time((DERUTCTime) obj);
059: } else if (obj instanceof DERGeneralizedTime) {
060: return new Time((DERGeneralizedTime) obj);
061: }
062:
063: throw new IllegalArgumentException("unknown object in factory");
064: }
065:
066: public String getTime() {
067: if (time instanceof DERUTCTime) {
068: return ((DERUTCTime) time).getAdjustedTime();
069: } else {
070: return ((DERGeneralizedTime) time).getTime();
071: }
072: }
073:
074: public Date getDate() {
075: try {
076: if (time instanceof DERUTCTime) {
077: return ((DERUTCTime) time).getAdjustedDate();
078: } else {
079: return ((DERGeneralizedTime) time).getDate();
080: }
081: } catch (ParseException e) { // this should never happen
082: throw new IllegalStateException("invalid date string: "
083: + e.getMessage());
084: }
085: }
086:
087: /**
088: * Produce an object suitable for an ASN1OutputStream.
089: * <pre>
090: * Time ::= CHOICE {
091: * utcTime UTCTime,
092: * generalTime GeneralizedTime }
093: * </pre>
094: */
095: public DERObject toASN1Object() {
096: return time;
097: }
098:
099: public String toString() {
100: return getTime();
101: }
102: }
|