summary refs log tree commit diff
path: root/crypto/src/asn1/crmf/OptionalValidity.cs
blob: 290d1905ea78a274b6f0850aab01c289baa5aa91 (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
using System;

using Org.BouncyCastle.Asn1.X509;

namespace Org.BouncyCastle.Asn1.Crmf
{
    public class OptionalValidity
        : Asn1Encodable
    {
        public static OptionalValidity GetInstance(object obj)
        {
            if (obj == null)
                return null;
            if (obj is OptionalValidity optionalValidity)
                return optionalValidity;
            return new OptionalValidity(Asn1Sequence.GetInstance(obj));
        }

        public static OptionalValidity GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit)
        {
            return new OptionalValidity(Asn1Sequence.GetInstance(taggedObject, declaredExplicit));
        }

        private readonly Time m_notBefore;
        private readonly Time m_notAfter;

        private OptionalValidity(Asn1Sequence seq)
        {
            // TODO Enforce "at least one MUST be present"?

            int count = seq.Count;
            if (count < 0 || count > 2)
                throw new ArgumentException("Bad sequence size: " + count, nameof(seq));

            int pos = 0;

            m_notBefore = Asn1Utilities.ReadOptionalContextTagged(seq, ref pos, 0, true, Time.GetInstance);
            m_notAfter = Asn1Utilities.ReadOptionalContextTagged(seq, ref pos, 1, true, Time.GetInstance);

            if (pos != count)
                throw new ArgumentException("Unexpected elements in sequence", nameof(seq));
        }

        public OptionalValidity(Time notBefore, Time notAfter)
        {
            // TODO Enforce "at least one MUST be present"?
            m_notBefore = notBefore;
            m_notAfter = notAfter;
        }

        public virtual Time NotBefore => m_notBefore;

        public virtual Time NotAfter => m_notAfter;

        /**
         * <pre>
         * OptionalValidity ::= SEQUENCE {
         *                        notBefore  [0] Time OPTIONAL,
         *                        notAfter   [1] Time OPTIONAL } --at least one MUST be present
         * </pre>
         * @return a basic ASN.1 object representation.
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(2);
            v.AddOptionalTagged(true, 0, m_notBefore);
            v.AddOptionalTagged(true, 1, m_notAfter);
            return new DerSequence(v);
        }
    }
}