summary refs log tree commit diff
path: root/crypto/src/openpgp/PgpPublicKeyRingBundle.cs
blob: 1940c979e4778702fa179cb2e989bf67d648f59f (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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;

namespace Org.BouncyCastle.Bcpg.OpenPgp
{
    /// <remarks>
    /// Often a PGP key ring file is made up of a succession of master/sub-key key rings.
    /// If you want to read an entire public key file in one hit this is the class for you.
    /// </remarks>
    public class PgpPublicKeyRingBundle
    {
        private readonly IDictionary<long, PgpPublicKeyRing> m_pubRings;
        private readonly IList<long> m_order;

		private PgpPublicKeyRingBundle(IDictionary<long, PgpPublicKeyRing> pubRings, IList<long> order)
        {
            m_pubRings = pubRings;
            m_order = order;
        }

		public PgpPublicKeyRingBundle(byte[] encoding)
            : this(new MemoryStream(encoding, false))
        {
        }

		/// <summary>Build a PgpPublicKeyRingBundle from the passed in input stream.</summary>
		/// <param name="inputStream">Input stream containing data.</param>
		/// <exception cref="IOException">If a problem parsing the stream occurs.</exception>
		/// <exception cref="PgpException">If an object is encountered which isn't a PgpPublicKeyRing.</exception>
		public PgpPublicKeyRingBundle(Stream inputStream)
			: this(new PgpObjectFactory(inputStream).AllPgpObjects())
		{
        }

		public PgpPublicKeyRingBundle(IEnumerable<PgpObject> e)
        {
			m_pubRings = new Dictionary<long, PgpPublicKeyRing>();
			m_order = new List<long>();

			foreach (var obj in e)
            {
                // Marker packets must be ignored
                if (obj is PgpMarker)
                    continue;

				if (!(obj is PgpPublicKeyRing pgpPub))
					throw new PgpException(Platform.GetTypeName(obj) + " found where PgpPublicKeyRing expected");

				long key = pgpPub.GetPublicKey().KeyId;
                m_pubRings.Add(key, pgpPub);
				m_order.Add(key);
            }
        }

		/// <summary>Return the number of key rings in this collection.</summary>
        public int Count
        {
			get { return m_order.Count; }
        }

		/// <summary>Allow enumeration of the public key rings making up this collection.</summary>
        public IEnumerable<PgpPublicKeyRing> GetKeyRings()
        {
			return CollectionUtilities.Proxy(KeyRings);
        }

		/// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary>
		/// <param name="userId">The user ID to be matched.</param>
		/// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns>
		public IEnumerable<PgpPublicKeyRing> GetKeyRings(string userId)
		{
			return GetKeyRings(userId, false, false);
		}

		/// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary>
		/// <param name="userId">The user ID to be matched.</param>
		/// <param name="matchPartial">If true, userId need only be a substring of an actual ID string to match.</param>
		/// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns>
        public IEnumerable<PgpPublicKeyRing> GetKeyRings(string userId, bool matchPartial)
        {
			return GetKeyRings(userId, matchPartial, false);
        }

		/// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary>
		/// <param name="userID">The user ID to be matched.</param>
		/// <param name="matchPartial">If true, userId need only be a substring of an actual ID string to match.</param>
		/// <param name="ignoreCase">If true, case is ignored in user ID comparisons.</param>
		/// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns>
		public IEnumerable<PgpPublicKeyRing> GetKeyRings(string userID, bool matchPartial, bool ignoreCase)
		{
			var compareInfo = CultureInfo.InvariantCulture.CompareInfo;
			var compareOptions = ignoreCase ? CompareOptions.OrdinalIgnoreCase : CompareOptions.Ordinal;

			foreach (PgpPublicKeyRing pubRing in KeyRings)
			{
				foreach (string nextUserID in pubRing.GetPublicKey().GetUserIds())
				{
					if (matchPartial)
					{
						if (compareInfo.IndexOf(nextUserID, userID, compareOptions) >= 0)
							yield return pubRing;
					}
					else
					{
						if (compareInfo.Compare(nextUserID, userID, compareOptions) == 0)
							yield return pubRing;
					}
				}
			}
		}

		/// <summary>Return the PGP public key associated with the given key id.</summary>
		/// <param name="keyId">The ID of the public key to return.</param>
        public PgpPublicKey GetPublicKey(long keyId)
        {
            foreach (PgpPublicKeyRing pubRing in KeyRings)
            {
                PgpPublicKey pub = pubRing.GetPublicKey(keyId);
				if (pub != null)
                    return pub;
            }

			return null;
        }

		/// <summary>Return the public key ring which contains the key referred to by keyId</summary>
		/// <param name="keyId">key ID to match against</param>
        public PgpPublicKeyRing GetPublicKeyRing(long keyId)
        {
			if (m_pubRings.TryGetValue(keyId, out var keyRing))
				return keyRing;

			foreach (PgpPublicKeyRing pubRing in KeyRings)
            {
                if (pubRing.GetPublicKey(keyId) != null)
                    return pubRing;
            }

			return null;
        }

        /// <summary>Return the PGP public key associated with the given key fingerprint.</summary>
        /// <param name="fingerprint">the public key fingerprint to match against.</param>
        public PgpPublicKey GetPublicKey(byte[] fingerprint)
        {
            foreach (PgpPublicKeyRing pubRing in KeyRings)
            {
                PgpPublicKey pub = pubRing.GetPublicKey(fingerprint);
                if (pub != null)
                    return pub;
            }

            return null;
        }

        /// <summary>Return the public key ring which contains the key associated with the given key fingerprint.
        /// </summary>
        /// <param name="fingerprint">the public key fingerprint to match against.</param>
        public PgpPublicKeyRing GetPublicKeyRing(byte[] fingerprint)
        {
            foreach (PgpPublicKeyRing pubRing in KeyRings)
            {
                if (pubRing.GetPublicKey(fingerprint) != null)
                    return pubRing;
            }

            return null;
        }

        /// <summary>
        /// Return true if a key matching the passed in key ID is present, false otherwise.
        /// </summary>
        /// <param name="keyID">key ID to look for.</param>
        public bool Contains(long keyID)
		{
			return GetPublicKey(keyID) != null;
		}

		public byte[] GetEncoded()
        {
            MemoryStream bOut = new MemoryStream();
			Encode(bOut);
			return bOut.ToArray();
        }

		public void Encode(Stream outStr)
        {
			BcpgOutputStream bcpgOut = BcpgOutputStream.Wrap(outStr);

			foreach (long key in m_order)
            {
                m_pubRings[key].Encode(bcpgOut);
            }
        }

        private ICollection<PgpPublicKeyRing> KeyRings => m_pubRings.Values;

        /// <summary>
        /// Return a new bundle containing the contents of the passed in bundle and
        /// the passed in public key ring.
        /// </summary>
        /// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be added to.</param>
        /// <param name="publicKeyRing">The key ring to be added.</param>
        /// <returns>A new <c>PgpPublicKeyRingBundle</c> merging the current one with the passed in key ring.</returns>
        /// <exception cref="ArgumentException">If the keyId for the passed in key ring is already present.</exception>
        public static PgpPublicKeyRingBundle AddPublicKeyRing(PgpPublicKeyRingBundle bundle,
            PgpPublicKeyRing publicKeyRing)
        {
            long key = publicKeyRing.GetPublicKey().KeyId;

			if (bundle.m_pubRings.ContainsKey(key))
                throw new ArgumentException("Bundle already contains a key with a keyId for the passed in ring.");

			var newPubRings = new Dictionary<long, PgpPublicKeyRing>(bundle.m_pubRings);
            var newOrder = new List<long>(bundle.m_order);

			newPubRings[key] = publicKeyRing;
			newOrder.Add(key);

			return new PgpPublicKeyRingBundle(newPubRings, newOrder);
        }

		/// <summary>
		/// Return a new bundle containing the contents of the passed in bundle with
		/// the passed in public key ring removed.
		/// </summary>
		/// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be removed from.</param>
		/// <param name="publicKeyRing">The key ring to be removed.</param>
		/// <returns>A new <c>PgpPublicKeyRingBundle</c> not containing the passed in key ring.</returns>
		/// <exception cref="ArgumentException">If the keyId for the passed in key ring is not present.</exception>
        public static PgpPublicKeyRingBundle RemovePublicKeyRing(PgpPublicKeyRingBundle bundle,
            PgpPublicKeyRing publicKeyRing)
        {
            long key = publicKeyRing.GetPublicKey().KeyId;

			if (!bundle.m_pubRings.ContainsKey(key))
                throw new ArgumentException("Bundle does not contain a key with a keyId for the passed in ring.");

			var newPubRings = new Dictionary<long, PgpPublicKeyRing>(bundle.m_pubRings);
			var newOrder = new List<long>(bundle.m_order);

			newPubRings.Remove(key);
			newOrder.Remove(key);

			return new PgpPublicKeyRingBundle(newPubRings, newOrder);
        }
    }
}