summary refs log tree commit diff
path: root/crypto/src/openpgp/PgpSecretKeyRing.cs
blob: a070aa132e4cb4a394d51233259086c6387997c8 (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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
using System;
using System.Collections.Generic;
using System.IO;

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

namespace Org.BouncyCastle.Bcpg.OpenPgp
{
    /// <remarks>
    /// Class to hold a single master secret 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>PgpSecretKeyRingBundle</c> class.
    /// </p>
    /// </remarks>
    public class PgpSecretKeyRing
        : PgpKeyRing
    {
        private readonly IList<PgpSecretKey> keys;
        private readonly IList<PgpPublicKey> extraPubKeys;

        internal PgpSecretKeyRing(
            IList<PgpSecretKey> keys)
            : this(keys, new List<PgpPublicKey>())
        {
        }

        private PgpSecretKeyRing(
            IList<PgpSecretKey> keys,
            IList<PgpPublicKey> extraPubKeys)
        {
            this.keys = keys;
            this.extraPubKeys = extraPubKeys;
        }

        public PgpSecretKeyRing(
            byte[] encoding)
            : this(new MemoryStream(encoding))
        {
        }

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

            BcpgInputStream bcpgInput = BcpgInputStream.Wrap(inputStream);

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

            SecretKeyPacket secret = (SecretKeyPacket) bcpgInput.ReadPacket();

            //
            // ignore GPG comment packets if found.
            //
            while (bcpgInput.NextPacketTag() == PacketTag.Experimental2)
            {
                bcpgInput.ReadPacket();
            }

            TrustPacket trust = ReadOptionalTrustPacket(bcpgInput);

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

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

            keys.Add(new PgpSecretKey(secret,
                new PgpPublicKey(secret.PublicKeyPacket, trust, keySigs, ids, idTrusts, idSigs)));

            // Read subkeys
            while (bcpgInput.NextPacketTag() == PacketTag.SecretSubkey
                || bcpgInput.NextPacketTag() == PacketTag.PublicSubkey)
            {
                if (bcpgInput.NextPacketTag() == PacketTag.SecretSubkey)
                {
                    SecretSubkeyPacket sub = (SecretSubkeyPacket) bcpgInput.ReadPacket();

                    //
                    // ignore GPG comment packets if found.
                    //
                    while (bcpgInput.NextPacketTag() == PacketTag.Experimental2)
                    {
                        bcpgInput.ReadPacket();
                    }

                    TrustPacket subTrust = ReadOptionalTrustPacket(bcpgInput);
                    var sigList = ReadSignaturesAndTrust(bcpgInput);

                    keys.Add(new PgpSecretKey(sub, new PgpPublicKey(sub.PublicKeyPacket, subTrust, sigList)));
                }
                else
                {
                    PublicSubkeyPacket sub = (PublicSubkeyPacket) bcpgInput.ReadPacket();

                    TrustPacket subTrust = ReadOptionalTrustPacket(bcpgInput);
                    var sigList = ReadSignaturesAndTrust(bcpgInput);

                    extraPubKeys.Add(new PgpPublicKey(sub, subTrust, sigList));
                }
            }
        }

        /// <summary>Return the public key for the master key.</summary>
        public PgpPublicKey GetPublicKey()
        {
            return keys[0].PublicKey;
        }

        /**
         * Return any keys carrying a signature issued by the key represented by keyID.
         *
         * @param keyID the key id to be matched against.
         * @return an iterator (possibly empty) of PGPPublicKey objects carrying signatures from keyID.
         */
        public IEnumerable<PgpPublicKey> GetKeysWithSignaturesBy(long keyID)
        {
            var keysWithSigs = new List<PgpPublicKey>();

            foreach (var k in GetPublicKeys())
            {
                var sigIt = k.GetSignaturesForKeyID(keyID).GetEnumerator();

                if (sigIt.MoveNext())
                {
                    keysWithSigs.Add(k);
                }
            }

            return CollectionUtilities.Proxy(keysWithSigs);
        }

        public IEnumerable<PgpPublicKey> GetPublicKeys()
        {
            var pubKeys = new List<PgpPublicKey>();

            foreach (var secretKey in keys)
            {
                pubKeys.Add(secretKey.PublicKey);
            }

            pubKeys.AddRange(extraPubKeys);

            return CollectionUtilities.Proxy(pubKeys);
        }

        /// <summary>Return the master private key.</summary>
        public PgpSecretKey GetSecretKey()
        {
            return keys[0];
        }

        /// <summary>Allows enumeration of the secret keys.</summary>
        /// <returns>An <c>IEnumerable</c> of <c>PgpSecretKey</c> objects.</returns>
        public IEnumerable<PgpSecretKey> GetSecretKeys()
        {
            return CollectionUtilities.Proxy(keys);
        }

        public PgpSecretKey GetSecretKey(long keyId)
        {
            foreach (PgpSecretKey k in keys)
            {
                if (keyId == k.KeyId)
                    return k;
            }

            return null;
        }

        /// <summary>
        /// Return an iterator of the public keys in the secret key ring that
        /// have no matching private key. At the moment only personal certificate data
        /// appears in this fashion.
        /// </summary>
        /// <returns>An <c>IEnumerable</c> of unattached, or extra, public keys.</returns>
        public IEnumerable<PgpPublicKey> GetExtraPublicKeys()
        {
            return CollectionUtilities.Proxy(extraPubKeys);
        }

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

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

            foreach (PgpSecretKey key in keys)
            {
                key.Encode(outStr);
            }
            foreach (PgpPublicKey extraPubKey in extraPubKeys)
            {
                extraPubKey.Encode(outStr);
            }
        }

        /// <summary>
        /// Replace the public key set on the secret ring with the corresponding key off the public ring.
        /// </summary>
        /// <param name="secretRing">Secret ring to be changed.</param>
        /// <param name="publicRing">Public ring containing the new public key set.</param>
        public static PgpSecretKeyRing ReplacePublicKeys(PgpSecretKeyRing secretRing, PgpPublicKeyRing publicRing)
        {
            var newList = new List<PgpSecretKey>(secretRing.keys.Count);

            foreach (PgpSecretKey sk in secretRing.keys)
            {
                PgpPublicKey pk = publicRing.GetPublicKey(sk.KeyId);

                newList.Add(PgpSecretKey.ReplacePublicKey(sk, pk));
            }

            return new PgpSecretKeyRing(newList);
        }

        /// <summary>
        /// Return a copy of the passed in secret key ring, with the master key and sub keys encrypted
        /// using a new password and the passed in algorithm.
        /// </summary>
        /// <param name="ring">The <c>PgpSecretKeyRing</c> to be copied.</param>
        /// <param name="oldPassPhrase">The current password for key.</param>
        /// <param name="newPassPhrase">The new password for the key.</param>
        /// <param name="newEncAlgorithm">The algorithm to be used for the encryption.</param>
        /// <param name="rand">Source of randomness.</param>
        public static PgpSecretKeyRing CopyWithNewPassword(
            PgpSecretKeyRing			ring,
            char[]						oldPassPhrase,
            char[]						newPassPhrase,
            SymmetricKeyAlgorithmTag	newEncAlgorithm,
            SecureRandom				rand)
        {
            var newKeys = new List<PgpSecretKey>(ring.keys.Count);

            foreach (PgpSecretKey secretKey in ring.GetSecretKeys())
            {
                if (secretKey.IsPrivateKeyEmpty)
                {
                    newKeys.Add(secretKey);
                }
                else
                {
                    newKeys.Add(PgpSecretKey.CopyWithNewPassword(secretKey, oldPassPhrase, newPassPhrase,
                        newEncAlgorithm, rand));
                }
            }

            return new PgpSecretKeyRing(newKeys, ring.extraPubKeys);
        }

        /// <summary>
        /// Returns a new key ring with the secret key passed in either added or
        /// replacing an existing one with the same key ID.
        /// </summary>
        /// <param name="secRing">The secret key ring to be modified.</param>
        /// <param name="secKey">The secret key to be inserted.</param>
        /// <returns>A new <c>PgpSecretKeyRing</c></returns>
        public static PgpSecretKeyRing InsertSecretKey(
            PgpSecretKeyRing  secRing,
            PgpSecretKey      secKey)
        {
            var keys = new List<PgpSecretKey>(secRing.keys);
            bool found = false;
            bool masterFound = false;

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

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

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

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

            return new PgpSecretKeyRing(keys, secRing.extraPubKeys);
        }

        /// <summary>Returns a new key ring with the secret key passed in removed from the key ring.</summary>
        /// <param name="secRing">The secret key ring to be modified.</param>
        /// <param name="secKey">The secret key to be removed.</param>
        /// <returns>A new <c>PgpSecretKeyRing</c>, or null if secKey is not found.</returns>
        public static PgpSecretKeyRing RemoveSecretKey(
            PgpSecretKeyRing  secRing,
            PgpSecretKey      secKey)
        {
            var keys = new List<PgpSecretKey>(secRing.keys);
            bool found = false;

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

                if (key.KeyId == secKey.KeyId)
                {
                    found = true;
                    keys.RemoveAt(i);
                }
            }

            return found ? new PgpSecretKeyRing(keys, secRing.extraPubKeys) : null;
        }
    }
}