01: package org.bouncycastle.asn1.cms;
02:
03: import org.bouncycastle.asn1.ASN1Encodable;
04: import org.bouncycastle.asn1.ASN1TaggedObject;
05: import org.bouncycastle.asn1.DERGeneralizedTime;
06: import org.bouncycastle.asn1.DERObject;
07: import org.bouncycastle.asn1.DERUTCTime;
08:
09: import java.text.ParseException;
10: import java.text.SimpleDateFormat;
11: import java.util.Date;
12: import java.util.SimpleTimeZone;
13:
14: public class Time extends ASN1Encodable {
15: DERObject time;
16:
17: public static Time getInstance(ASN1TaggedObject obj,
18: boolean explicit) {
19: return getInstance(obj.getObject());
20: }
21:
22: public Time(DERObject time) {
23: if (!(time instanceof DERUTCTime)
24: && !(time instanceof DERGeneralizedTime)) {
25: throw new IllegalArgumentException(
26: "unknown object passed to Time");
27: }
28:
29: this .time = time;
30: }
31:
32: /**
33: * creates a time object from a given date - if the date is between 1950
34: * and 2049 a UTCTime object is generated, otherwise a GeneralizedTime
35: * is used.
36: */
37: public Time(Date date) {
38: SimpleTimeZone tz = new SimpleTimeZone(0, "Z");
39: SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmss");
40:
41: dateF.setTimeZone(tz);
42:
43: String d = dateF.format(date) + "Z";
44: int year = Integer.parseInt(d.substring(0, 4));
45:
46: if (year < 1950 || year > 2049) {
47: time = new DERGeneralizedTime(d);
48: } else {
49: time = new DERUTCTime(d.substring(2));
50: }
51: }
52:
53: public static Time getInstance(Object obj) {
54: if (obj instanceof Time) {
55: return (Time) obj;
56: } else if (obj instanceof DERUTCTime) {
57: return new Time((DERUTCTime) obj);
58: } else if (obj instanceof DERGeneralizedTime) {
59: return new Time((DERGeneralizedTime) obj);
60: }
61:
62: throw new IllegalArgumentException("unknown object in factory");
63: }
64:
65: public String getTime() {
66: if (time instanceof DERUTCTime) {
67: return ((DERUTCTime) time).getAdjustedTime();
68: } else {
69: return ((DERGeneralizedTime) time).getTime();
70: }
71: }
72:
73: public Date getDate() {
74: try {
75: if (time instanceof DERUTCTime) {
76: return ((DERUTCTime) time).getAdjustedDate();
77: } else {
78: return ((DERGeneralizedTime) time).getDate();
79: }
80: } catch (ParseException e) { // this should never happen
81: throw new IllegalStateException("invalid date string: "
82: + e.getMessage());
83: }
84: }
85:
86: /**
87: * Produce an object suitable for an ASN1OutputStream.
88: * <pre>
89: * Time ::= CHOICE {
90: * utcTime UTCTime,
91: * generalTime GeneralizedTime }
92: * </pre>
93: */
94: public DERObject toASN1Object() {
95: return time;
96: }
97: }
|