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

namespace Org.BouncyCastle.Asn1
{
	public abstract class Asn1Encodable
		: IAsn1Convertible
    {
		public const string Der = "DER";
		public const string Ber = "BER";

		public byte[] GetEncoded()
        {
            MemoryStream bOut = new MemoryStream();
            Asn1OutputStream aOut = new Asn1OutputStream(bOut);

            ToAsn1Object().Encode(aOut);

            return bOut.ToArray();
        }

        public byte[] GetEncoded(string encoding)
        {
            if (encoding.Equals(Der))
            {
                MemoryStream bOut = new MemoryStream();
                DerOutputStream dOut = new DerOutputStream(bOut);

                Asn1Object asn1Object = ToAsn1Object();

                Asn1Set asn1Set = asn1Object as Asn1Set;
                if (null != asn1Set)
                {
                    /*
                     * NOTE: Even a DerSet isn't necessarily already in sorted order (particularly from DerSetParser),
                     * so all sets have to be converted here.
                     */
                    asn1Object = new DerSet(asn1Set.elements);
                }

                asn1Object.Encode(dOut);

                return bOut.ToArray();
            }

            return GetEncoded();
        }

        /**
		* Return the DER encoding of the object, null if the DER encoding can not be made.
		*
		* @return a DER byte array, null otherwise.
		*/
        public byte[] GetDerEncoded()
		{
			try
			{
				return GetEncoded(Der);
			}
			catch (IOException)
			{
				return null;
			}
		}

		public sealed override int GetHashCode()
		{
			return ToAsn1Object().CallAsn1GetHashCode();
		}

		public sealed override bool Equals(
			object obj)
		{
			if (obj == this)
				return true;

			IAsn1Convertible other = obj as IAsn1Convertible;

			if (other == null)
				return false;

			Asn1Object o1 = ToAsn1Object();
			Asn1Object o2 = other.ToAsn1Object();

			return o1 == o2 || (null != o2 && o1.CallAsn1Equals(o2));
		}

		public abstract Asn1Object ToAsn1Object();
    }
}