summary refs log tree commit diff
path: root/crypto/src/openpgp/PgpPublicKeyRing.cs
blob: 46eecd726e06966c54d46ee9cdd5d67554825710 (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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
using System;
using System.Collections.Generic;
using System.IO;

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

namespace Org.BouncyCastle.Bcpg.OpenPgp
{
    /// <remarks>
    /// Class to hold a single master public key and its subkeys.
    /// <p>
    /// Often PGP keyring files consist of multiple master keys, if you are trying to process
    /// or construct one of these you should use the <c>PgpPublicKeyRingBundle</c> class.
    /// </p>
    /// </remarks>
    public class PgpPublicKeyRing
        : PgpKeyRing
    {
        private readonly IList<PgpPublicKey> keys;

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

        internal PgpPublicKeyRing(IList<PgpPublicKey> pubKeys)
        {
            this.keys = pubKeys;
        }

        public PgpPublicKeyRing(
            Stream inputStream)
        {
            this.keys = new List<PgpPublicKey>();

            BcpgInputStream bcpgInput = BcpgInputStream.Wrap(inputStream);

            PacketTag initialTag = bcpgInput.SkipMarkerPackets();
            if (initialTag != PacketTag.PublicKey && initialTag != PacketTag.PublicSubkey)
            {
                throw new IOException("public key ring doesn't start with public key tag: "
                    + "tag 0x" + ((int)initialTag).ToString("X"));
            }

            PublicKeyPacket pubPk = ReadPublicKeyPacket(bcpgInput);
            TrustPacket trustPk = ReadOptionalTrustPacket(bcpgInput);

            // direct signatures and revocations
            var keySigs = ReadSignaturesAndTrust(bcpgInput);

            ReadUserIDs(bcpgInput, out var ids, out var idTrusts, out var idSigs);

            keys.Add(new PgpPublicKey(pubPk, trustPk, keySigs, ids, idTrusts, idSigs));


            // Read subkeys
            while (bcpgInput.NextPacketTag() == PacketTag.PublicSubkey)
            {
                keys.Add(ReadSubkey(bcpgInput));
            }
        }

        /// <summary>Return the first public key in the ring.</summary>
        public virtual PgpPublicKey GetPublicKey()
        {
            return keys[0];
        }

        /// <summary>Return the public key referred to by the passed in key ID if it is present.</summary>
        public virtual PgpPublicKey GetPublicKey(long keyId)
        {
            foreach (PgpPublicKey k in keys)
            {
                if (keyId == k.KeyId)
                    return k;
            }

            return null;
        }

        /// <summary>Allows enumeration of all the public keys.</summary>
        /// <returns>An <c>IEnumerable</c> of <c>PgpPublicKey</c> objects.</returns>
        public virtual IEnumerable<PgpPublicKey> GetPublicKeys()
        {
            return CollectionUtilities.Proxy(keys);
        }

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

            Encode(bOut);

            return bOut.ToArray();
        }

        public virtual void Encode(
            Stream outStr)
        {
            if (outStr == null)
                throw new ArgumentNullException("outStr");

            foreach (PgpPublicKey k in keys)
            {
                k.Encode(outStr);
            }
        }

        /// <summary>
        /// Returns a new key ring with the public key passed in either added or
        /// replacing an existing one.
        /// </summary>
        /// <param name="pubRing">The public key ring to be modified.</param>
        /// <param name="pubKey">The public key to be inserted.</param>
        /// <returns>A new <c>PgpPublicKeyRing</c></returns>
        public static PgpPublicKeyRing InsertPublicKey(
            PgpPublicKeyRing	pubRing,
            PgpPublicKey		pubKey)
        {
            var keys = new List<PgpPublicKey>(pubRing.keys);
            bool found = false;
            bool masterFound = false;

            for (int i = 0; i != keys.Count; i++)
            {
                PgpPublicKey key = keys[i];

                if (key.KeyId == pubKey.KeyId)
                {
                    found = true;
                    keys[i] = pubKey;
                }
                if (key.IsMasterKey)
                {
                    masterFound = true;
                }
            }

            if (!found)
            {
                if (pubKey.IsMasterKey)
                {
                    if (masterFound)
                        throw new ArgumentException("cannot add a master key to a ring that already has one");

                    keys.Insert(0, pubKey);
                }
                else
                {
                    keys.Add(pubKey);
                }
            }

            return new PgpPublicKeyRing(keys);
        }

        /// <summary>Returns a new key ring with the public key passed in removed from the key ring.</summary>
        /// <param name="pubRing">The public key ring to be modified.</param>
        /// <param name="pubKey">The public key to be removed.</param>
        /// <returns>A new <c>PgpPublicKeyRing</c>, or null if pubKey is not found.</returns>
        public static PgpPublicKeyRing RemovePublicKey(PgpPublicKeyRing pubRing, PgpPublicKey pubKey)
        {
            int count = pubRing.keys.Count;
            long keyID = pubKey.KeyId;

            var result = new List<PgpPublicKey>(count);
            bool found = false;

            foreach (var key in pubRing.keys)
            {
                if (key.KeyId == keyID)
                {
                    found = true;
                    continue;
                }

                result.Add(key);
            }

            return found ? new PgpPublicKeyRing(result) : null;
        }

        internal static PublicKeyPacket ReadPublicKeyPacket(BcpgInputStream bcpgInput)
        {
            Packet packet = bcpgInput.ReadPacket();
            if (!(packet is PublicKeyPacket publicKeyPacket))
                throw new IOException("unexpected packet in stream: " + packet);

            return publicKeyPacket;
        }

        internal static PgpPublicKey ReadSubkey(BcpgInputStream bcpgInput)
        {
            PublicKeyPacket	pk = ReadPublicKeyPacket(bcpgInput);
            TrustPacket kTrust = ReadOptionalTrustPacket(bcpgInput);

            // PGP 8 actually leaves out the signature.
            var sigList = ReadSignaturesAndTrust(bcpgInput);

            return new PgpPublicKey(pk, kTrust, sigList);
        }

        /**
         * Join two copies of the same certificate.
         * The certificates must have the same primary key, but may carry different subkeys, user-ids and signatures.
         * The resulting certificate will carry the sum of both certificates subkeys, user-ids and signatures.
         * <br/>
         * This method will ignore trust packets on the second copy of the certificate and instead
         * copy the local certificate's trust packets to the joined certificate.
         *
         * @param first  local copy of the certificate
         * @param second remote copy of the certificate (e.g. from a key server)
         * @return joined key ring
         * @throws PGPException
         */
        public static PgpPublicKeyRing Join(PgpPublicKeyRing first, PgpPublicKeyRing second)
        {
            return Join(first, second, false, false);
        }

        /**
         * Join two copies of the same certificate.
         * The certificates must have the same primary key, but may carry different subkeys, user-ids and signatures.
         * The resulting certificate will carry the sum of both certificates subkeys, user-ids and signatures.
         * <br/>
         * For each subkey holds: If joinTrustPackets is set to true and the second key is carrying a trust packet,
         * the trust packet will be copied to the joined key.
         * Otherwise, the joined key will carry the trust packet of the local copy.
         *
         * @param first                      local copy of the certificate
         * @param second                     remote copy of the certificate (e.g. from a key server)
         * @param joinTrustPackets           if true, trust packets from the second certificate copy will be carried over into the joined certificate
         * @param allowSubkeySigsOnNonSubkey if true, the resulting joined certificate may carry subkey signatures on its primary key
         * @return joined certificate
         * @throws PGPException
         */
        public static PgpPublicKeyRing Join(PgpPublicKeyRing first, PgpPublicKeyRing second, bool joinTrustPackets,
            bool allowSubkeySigsOnNonSubkey)
        {
            if (!Arrays.AreEqual(first.GetPublicKey().GetFingerprint(), second.GetPublicKey().GetFingerprint()))
                throw new ArgumentException("Cannot merge certificates with differing primary keys.");

            var secondKeys = new HashSet<long>();
            foreach (var key in second.GetPublicKeys())
            {
                secondKeys.Add(key.KeyId);
            }

            var merged = new List<PgpPublicKey>();
            foreach (var key in first.GetPublicKeys())
            {
                var copy = second.GetPublicKey(key.KeyId);
                if (copy != null)
                {
                    merged.Add(PgpPublicKey.Join(key, copy, joinTrustPackets, allowSubkeySigsOnNonSubkey));
                    secondKeys.Remove(key.KeyId);
                }
                else
                {
                    merged.Add(key);
                }
            }

            foreach (var additionalKeyId in secondKeys)
            {
                merged.Add(second.GetPublicKey(additionalKeyId));
            }

            return new PgpPublicKeyRing(merged);
        }
    }
}