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

using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Bcpg
{
    /**
    * Basic type for a user attribute sub-packet.
    */
    public class UserAttributeSubpacket
    {
        internal readonly UserAttributeSubpacketTag	type;
        private readonly bool longLength;   // we preserve this as not everyone encodes length properly.
        protected readonly byte[] data;

        protected internal UserAttributeSubpacket(UserAttributeSubpacketTag type, byte[] data)
            : this(type, false, data)
        {
        }

        protected internal UserAttributeSubpacket(UserAttributeSubpacketTag type, bool forceLongLength, byte[] data)
        {
            this.type = type;
            this.longLength = forceLongLength;
            this.data = data;
        }

        public virtual UserAttributeSubpacketTag SubpacketType
        {
            get { return type; }
        }

        /**
        * return the generic data making up the packet.
        */
        public virtual byte[] GetData()
        {
            return data;
        }

        public virtual void Encode(Stream os)
        {
            int bodyLen = data.Length + 1;

            if (bodyLen < 192 && !longLength)
            {
                os.WriteByte((byte)bodyLen);
            }
            else if (bodyLen <= 8383 && !longLength)
            {
                bodyLen -= 192;

                os.WriteByte((byte)(((bodyLen >> 8) & 0xff) + 192));
                os.WriteByte((byte)bodyLen);
            }
            else
            {
                os.WriteByte(0xff);
                os.WriteByte((byte)(bodyLen >> 24));
                os.WriteByte((byte)(bodyLen >> 16));
                os.WriteByte((byte)(bodyLen >> 8));
                os.WriteByte((byte)bodyLen);
            }

            os.WriteByte((byte) type);
            os.Write(data, 0, data.Length);
        }

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

            UserAttributeSubpacket other = obj as UserAttributeSubpacket;

            if (other == null)
                return false;

            return type == other.type
                && Arrays.AreEqual(data, other.data);
        }

        public override int GetHashCode()
        {
            return type.GetHashCode() ^ Arrays.GetHashCode(data);
        }
    }
}