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

using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Asn1.Cms
{
    public class CcmParameters
        : Asn1Encodable
    {
        private const int DefaultIcvLen = 12;

        public static CcmParameters GetInstance(object obj)
        {
            if (obj == null)
                return null;
            if (obj is CcmParameters ccmParameters)
                return ccmParameters;
            return new CcmParameters(Asn1Sequence.GetInstance(obj));
        }

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

        private readonly byte[] m_nonce;
        private readonly int m_icvLen;

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

            m_nonce = Asn1OctetString.GetInstance(seq[0]).GetOctets();

            if (count > 1)
            {
                m_icvLen = DerInteger.GetInstance(seq[1]).IntValueExact;
            }
            else
            {
                m_icvLen = DefaultIcvLen;
            }
        }

        public CcmParameters(byte[] nonce, int icvLen)
        {
            m_nonce = Arrays.Clone(nonce);
            m_icvLen = icvLen;
        }

        public byte[] GetNonce() => Arrays.Clone(m_nonce);

        public int IcvLen => m_icvLen;

        public override Asn1Object ToAsn1Object()
        {
            var nonce = new DerOctetString(m_nonce);

            return m_icvLen == DefaultIcvLen
                ?   new DerSequence(nonce)
                :   new DerSequence(nonce, new DerInteger(m_icvLen));
        }
    }
}