summary refs log tree commit diff
path: root/crypto/src/asn1/Asn1GeneralizedTime.cs
blob: 139384c1a6be07e5e7a81592d5e72e63386fb016 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
using System;
using System.Globalization;
using System.IO;
using System.Text;

using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Asn1
{
    /**
     * Base class representing the ASN.1 GeneralizedTime type.
     * <p>
     * The main difference between these and UTC time is a 4 digit year.
     * </p><p>
     * One second resolution date+time on UTC timezone (Z)
     * with 4 digit year (valid from 0001 to 9999).
     * </p><p>
     * Timestamp format is:  yyyymmddHHMMSS'Z'
     * </p><p>
     * <h2>X.690</h2>
     * This is what is called "restricted string",
     * and it uses ASCII characters to encode digits and supplemental data.
     *
     * <h3>11: Restrictions on BER employed by both CER and DER</h3>
     * <h4>11.7 GeneralizedTime </h4>
     * </p><p>
     * <b>11.7.1</b> The encoding shall terminate with a "Z",
     * as described in the ITU-T Rec. X.680 | ISO/IEC 8824-1 clause on
     * GeneralizedTime.
     * </p><p>
     * <b>11.7.2</b> The seconds element shall always be present.
     * </p><p>
     * <b>11.7.3</b> The fractional-seconds elements, if present,
     * shall omit all trailing zeros; if the elements correspond to 0,
     * they shall be wholly omitted, and the decimal point element also
     * shall be omitted.
     * </p>
     */
    public class Asn1GeneralizedTime
        : Asn1Object
    {
        internal class Meta : Asn1UniversalType
        {
            internal static readonly Asn1UniversalType Instance = new Meta();

            private Meta() : base(typeof(Asn1GeneralizedTime), Asn1Tags.GeneralizedTime) { }

            internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString)
            {
                return CreatePrimitive(octetString.GetOctets());
            }
        }

        public static Asn1GeneralizedTime GetInstance(object obj)
        {
            if (obj == null)
                return null;

            if (obj is Asn1GeneralizedTime asn1GeneralizedTime)
                return asn1GeneralizedTime;

            if (obj is IAsn1Convertible asn1Convertible)
            {
                Asn1Object asn1Object = asn1Convertible.ToAsn1Object();
                if (asn1Object is Asn1GeneralizedTime converted)
                    return converted;
            }
            else if (obj is byte[] bytes)
            {
                try
                {
                    return (Asn1GeneralizedTime)Meta.Instance.FromByteArray(bytes);
                }
                catch (IOException e)
                {
                    throw new ArgumentException("failed to construct generalized time from byte[]: " + e.Message);
                }
            }

            throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), nameof(obj));
        }

        public static Asn1GeneralizedTime GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit)
        {
            return (Asn1GeneralizedTime)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit);
        }

        internal readonly byte[] m_contents;

        public Asn1GeneralizedTime(string time)
        {
            m_contents = Strings.ToByteArray(time);

            try
            {
                ToDateTime();
            }
            catch (FormatException e)
            {
                throw new ArgumentException("invalid date string: " + e.Message);
            }
        }

        public Asn1GeneralizedTime(DateTime time)
        {
            DateTime utc = time.ToUniversalTime();
            var formatStr = @"yyyyMMddHHmmss\Z";
            var formatProvider = DateTimeFormatInfo.InvariantInfo;
            string utcString = utc.ToString(formatStr, formatProvider);
            m_contents = Strings.ToByteArray(utcString);
        }

        // TODO Custom locale constructor?
        //public Asn1GeneralizedTime(DateTime time, Locale locale)
        //{
        //    SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmss\Z", locale);

        //    dateF.setTimeZone(new SimpleTimeZone(0, "Z"));

        //    this.contents = Strings.toByteArray(dateF.format(time));
        //}

        internal Asn1GeneralizedTime(byte[] bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes));
            if (bytes.Length < 4)
                throw new ArgumentException("GeneralizedTime string too short", nameof(bytes));

            m_contents = bytes;

            if (!(IsDigit(0) && IsDigit(1) && IsDigit(2) && IsDigit(3)))
                throw new ArgumentException("illegal characters in GeneralizedTime string", nameof(bytes));
        }

        public string TimeString => Strings.FromByteArray(m_contents);

        public string GetTime()
        {
            string stime = Strings.FromByteArray(m_contents);

            //
            // standardise the format.
            //
            if (stime[stime.Length - 1] == 'Z')
                return stime.Substring(0, stime.Length - 1) + "GMT+00:00";

            int signPos = stime.Length - 6;
            char sign = stime[signPos];
            if ((sign == '-' || sign == '+') && stime.IndexOf("GMT") == signPos - 3)
            {
                // already a GMT string!
                return stime;
            }

            signPos = stime.Length - 5;
            sign = stime[signPos];
            if (sign == '-' || sign == '+')
            {
                return stime.Substring(0, signPos)
                    + "GMT"
                    + stime.Substring(signPos, 3)
                    + ":"
                    + stime.Substring(signPos + 3);
            }

            signPos = stime.Length - 3;
            sign = stime[signPos];
            if (sign == '-' || sign == '+')
            {
                return stime.Substring(0, signPos)
                    + "GMT"
                    + stime.Substring(signPos)
                    + ":00";
            }

            return stime + CalculateGmtOffset(stime);
        }

        private string CalculateGmtOffset(string stime)
        {
            TimeZoneInfo timeZone = TimeZoneInfo.Local;
            TimeSpan offset = timeZone.BaseUtcOffset;

            string sign = "+";
            if (offset.CompareTo(TimeSpan.Zero) < 0)
            {
                sign = "-";
                offset = offset.Duration();
            }

            int hours = offset.Hours;
            int minutes = offset.Minutes;

            try
            {
                if (timeZone.SupportsDaylightSavingTime)
                {
                    string d = stime + "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
                    string formatStr = CalculateGmtFormatString(d);

                    DateTime dateTime = ParseDateString(d, formatStr, makeUniversal: true);

                    if (timeZone.IsDaylightSavingTime(dateTime))
                    {
                        hours += sign.Equals("+") ? 1 : -1;
                    }
                }
            }
            catch (Exception)
            {
                // we'll do our best and ignore daylight savings
            }

            return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
        }

        private string CalculateGmtFormatString(string d)
        {
            if (HasFractionalSeconds())
            {
                int fCount = Platform.IndexOf(d, "GMT") - 1 - d.IndexOf('.');
                return @"yyyyMMddHHmmss." + FString(fCount) + @"'GMT'zzz";
            }

            if (HasSeconds())
                return @"yyyyMMddHHmmss'GMT'zzz";

            if (HasMinutes())
                return @"yyyyMMddHHmm'GMT'zzz";

            return @"yyyyMMddHH'GMT'zzz";
        }

        private string Convert(int time)
        {
            if (time < 10)
                return "0" + time;

            return time.ToString();
        }

        public DateTime ToDateTime()
        {
            string formatStr;
            string stime = Strings.FromByteArray(m_contents);
            string d = stime;
            bool makeUniversal = false;

            if (Platform.EndsWith(stime, "Z"))
            {
                if (HasFractionalSeconds())
                {
                    int fCount = d.Length - d.IndexOf('.') - 2;
                    formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"\Z";
                }
                else if (HasSeconds())
                {
                    formatStr = @"yyyyMMddHHmmss\Z";
                }
                else if (HasMinutes())
                {
                    formatStr = @"yyyyMMddHHmm\Z";
                }
                else
                {
                    formatStr = @"yyyyMMddHH\Z";
                }
            }
            else if (stime.IndexOf('-') > 0 || stime.IndexOf('+') > 0)
            {
                d = GetTime();
                formatStr = CalculateGmtFormatString(d);
                makeUniversal = true;
            }
            else
            {
                if (HasFractionalSeconds())
                {
                    int fCount = d.Length - 1 - d.IndexOf('.');
                    formatStr = @"yyyyMMddHHmmss." + FString(fCount);
                }
                else if (HasSeconds())
                {
                    formatStr = @"yyyyMMddHHmmss";
                }
                else if (HasMinutes())
                {
                    formatStr = @"yyyyMMddHHmm";
                }
                else
                {
                    formatStr = @"yyyyMMddHH";
                }
            }

            // TODO Epoch adjustment?
            //return DateUtil.epochAdjust(dateF.parse(d));
            return ParseDateString(d, formatStr, makeUniversal);
        }

        protected bool HasFractionalSeconds()
        {
            return m_contents.Length > 14 && m_contents[14] == '.';
        }

        protected bool HasSeconds()
        {
            return IsDigit(12) && IsDigit(13);
        }

        protected bool HasMinutes()
        {
            return IsDigit(10) && IsDigit(11);
        }

        private bool IsDigit(int pos)
        {
            return m_contents.Length > pos && m_contents[pos] >= '0' && m_contents[pos] <= '9';
        }

        internal override IAsn1Encoding GetEncoding(int encoding)
        {
            if (Asn1OutputStream.EncodingDer == encoding)
                return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.GeneralizedTime, GetDerTime());

            return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.GeneralizedTime, m_contents);
        }

        internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo)
        {
            if (Asn1OutputStream.EncodingDer == encoding)
                return new PrimitiveEncoding(tagClass, tagNo, GetDerTime());

            return new PrimitiveEncoding(tagClass, tagNo, m_contents);
        }

        protected override bool Asn1Equals(Asn1Object asn1Object)
        {
            if (!(asn1Object is Asn1GeneralizedTime that))
                return false;

            return Arrays.AreEqual(m_contents, that.m_contents);
        }

        protected override int Asn1GetHashCode()
        {
            return Arrays.GetHashCode(m_contents);
        }

        internal static Asn1GeneralizedTime CreatePrimitive(byte[] contents)
        {
            return new Asn1GeneralizedTime(contents);
        }

        internal byte[] GetDerTime()
        {
            if (m_contents[m_contents.Length - 1] != 'Z')
            {
                return m_contents; // TODO: is there a better way?
            }

            if (!HasMinutes())
            {
                byte[] derTime = new byte[m_contents.Length + 4];

                Array.Copy(m_contents, 0, derTime, 0, m_contents.Length - 1);
                Array.Copy(Strings.ToByteArray("0000Z"), 0, derTime, m_contents.Length - 1, 5);

                return derTime;
            }
            else if (!HasSeconds())
            {
                byte[] derTime = new byte[m_contents.Length + 2];

                Array.Copy(m_contents, 0, derTime, 0, m_contents.Length - 1);
                Array.Copy(Strings.ToByteArray("00Z"), 0, derTime, m_contents.Length - 1, 3);

                return derTime;
            }
            else if (HasFractionalSeconds())
            {
                int ind = m_contents.Length - 2;
                while (ind > 0 && m_contents[ind] == '0')
                {
                    ind--;
                }

                if (m_contents[ind] == '.')
                {
                    byte[] derTime = new byte[ind + 1];

                    Array.Copy(m_contents, 0, derTime, 0, ind);
                    derTime[ind] = (byte)'Z';

                    return derTime;
                }
                else
                {
                    byte[] derTime = new byte[ind + 2];

                    Array.Copy(m_contents, 0, derTime, 0, ind + 1);
                    derTime[ind + 1] = (byte)'Z';

                    return derTime;
                }
            }
            else
            {
                return m_contents;
            }
        }

        private static string FString(int count)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count; ++i)
            {
                sb.Append('f');
            }
            return sb.ToString();
        }

        private static DateTime ParseDateString(string s, string format, bool makeUniversal)
        {
            DateTimeStyles dateTimeStyles = DateTimeStyles.None;
            if (Platform.EndsWith(format, "Z"))
            {
                dateTimeStyles |= DateTimeStyles.AdjustToUniversal;
                dateTimeStyles |= DateTimeStyles.AssumeUniversal;
            }

            DateTime dt = DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, dateTimeStyles);

            return makeUniversal ? dt.ToUniversalTime() : dt;
        }
    }
}