summary refs log tree commit diff
path: root/crypto/src/bcpg/SignaturePacket.cs
blob: a0e8588b35eedae1ab388cc3e2ecdee95f7e0235 (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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
using System;
using System.Collections.Generic;
using System.IO;

using Org.BouncyCastle.Bcpg.Sig;
using Org.BouncyCastle.Utilities.Date;
using Org.BouncyCastle.Utilities.IO;

namespace Org.BouncyCastle.Bcpg
{
	/// <remarks>Generic signature packet.</remarks>
    public class SignaturePacket
        : ContainedPacket
    {
		private int						version;
        private int						signatureType;
        private long					creationTime;
        private long					keyId;
        private PublicKeyAlgorithmTag	keyAlgorithm;
        private HashAlgorithmTag		hashAlgorithm;
        private MPInteger[]				signature;
        private byte[]					fingerprint;
        private SignatureSubpacket[]	hashedData;
        private SignatureSubpacket[]	unhashedData;
		private byte[]					signatureEncoding;

		internal SignaturePacket(
            BcpgInputStream bcpgIn)
        {
            version = bcpgIn.ReadByte();

			if (version == 3 || version == 2)
            {
//                int l =
                bcpgIn.ReadByte();

				signatureType = bcpgIn.ReadByte();
                creationTime = (((long)bcpgIn.ReadByte() << 24) | ((long)bcpgIn.ReadByte() << 16)
                    | ((long)bcpgIn.ReadByte() << 8) | (uint)bcpgIn.ReadByte()) * 1000L;

				keyId |= (long)bcpgIn.ReadByte() << 56;
                keyId |= (long)bcpgIn.ReadByte() << 48;
                keyId |= (long)bcpgIn.ReadByte() << 40;
                keyId |= (long)bcpgIn.ReadByte() << 32;
                keyId |= (long)bcpgIn.ReadByte() << 24;
                keyId |= (long)bcpgIn.ReadByte() << 16;
                keyId |= (long)bcpgIn.ReadByte() << 8;
                keyId |= (uint)bcpgIn.ReadByte();

				keyAlgorithm = (PublicKeyAlgorithmTag) bcpgIn.ReadByte();
                hashAlgorithm = (HashAlgorithmTag) bcpgIn.ReadByte();
            }
            else if (version == 4)
            {
                signatureType = bcpgIn.ReadByte();
                keyAlgorithm = (PublicKeyAlgorithmTag) bcpgIn.ReadByte();
                hashAlgorithm = (HashAlgorithmTag) bcpgIn.ReadByte();

				int hashedLength = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte();
                byte[] hashed = new byte[hashedLength];

				bcpgIn.ReadFully(hashed);

				//
                // read the signature sub packet data.
                //
                SignatureSubpacketsParser sIn = new SignatureSubpacketsParser(
                    new MemoryStream(hashed, false));

                var v = new List<SignatureSubpacket>();

				SignatureSubpacket sub;
				while ((sub = sIn.ReadPacket()) != null)
                {
                    v.Add(sub);
                }

                hashedData = v.ToArray();

				foreach (var p in hashedData)
                {
                    if (p is IssuerKeyId issuerKeyId)
                    {
                        keyId = issuerKeyId.KeyId;
                    }
                    else if (p is SignatureCreationTime sigCreationTime)
                    {
                        creationTime = DateTimeUtilities.DateTimeToUnixMs(sigCreationTime.GetTime());
                    }
                }

				int unhashedLength = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte();
                byte[] unhashed = new byte[unhashedLength];

				bcpgIn.ReadFully(unhashed);

				sIn = new SignatureSubpacketsParser(new MemoryStream(unhashed, false));

				v.Clear();

				while ((sub = sIn.ReadPacket()) != null)
                {
                    v.Add(sub);
                }

                unhashedData = v.ToArray();

				foreach (var p in unhashedData)
                {
                    if (p is IssuerKeyId issuerKeyId)
                    {
                        keyId = issuerKeyId.KeyId;
                    }
                }
            }
            else
            {
                Streams.Drain(bcpgIn);

                throw new UnsupportedPacketVersionException("unsupported version: " + version);
            }

			fingerprint = new byte[2];
            bcpgIn.ReadFully(fingerprint);

			switch (keyAlgorithm)
            {
                case PublicKeyAlgorithmTag.RsaGeneral:
                case PublicKeyAlgorithmTag.RsaSign:
                    MPInteger v = new MPInteger(bcpgIn);
					signature = new MPInteger[1]{ v };
                    break;
				case PublicKeyAlgorithmTag.Dsa:
                    MPInteger r = new MPInteger(bcpgIn);
                    MPInteger s = new MPInteger(bcpgIn);
					signature = new MPInteger[2]{ r, s };
                    break;
                case PublicKeyAlgorithmTag.ElGamalEncrypt: // yep, this really does happen sometimes.
                case PublicKeyAlgorithmTag.ElGamalGeneral:
                    MPInteger p = new MPInteger(bcpgIn);
                    MPInteger g = new MPInteger(bcpgIn);
                    MPInteger y = new MPInteger(bcpgIn);
					signature = new MPInteger[3]{ p, g, y };
                    break;
                case PublicKeyAlgorithmTag.ECDsa:
                case PublicKeyAlgorithmTag.EdDsa:
                    MPInteger ecR = new MPInteger(bcpgIn);
                    MPInteger ecS = new MPInteger(bcpgIn);
                    signature = new MPInteger[2]{ ecR, ecS };
                    break;
                default:
					if (keyAlgorithm < PublicKeyAlgorithmTag.Experimental_1 || keyAlgorithm > PublicKeyAlgorithmTag.Experimental_11)
                        throw new IOException("unknown signature key algorithm: " + keyAlgorithm);

                    signature = null;
					MemoryStream bOut = new MemoryStream();
					int ch;
					while ((ch = bcpgIn.ReadByte()) >= 0)
					{
						bOut.WriteByte((byte) ch);
					}
					signatureEncoding = bOut.ToArray();
					break;
            }
        }

		/**
        * Generate a version 4 signature packet.
        *
        * @param signatureType
        * @param keyAlgorithm
        * @param hashAlgorithm
        * @param hashedData
        * @param unhashedData
        * @param fingerprint
        * @param signature
        */
        public SignaturePacket(
            int						signatureType,
            long					keyId,
            PublicKeyAlgorithmTag	keyAlgorithm,
            HashAlgorithmTag		hashAlgorithm,
            SignatureSubpacket[]	hashedData,
            SignatureSubpacket[]	unhashedData,
            byte[]					fingerprint,
            MPInteger[]				signature)
            : this(4, signatureType, keyId, keyAlgorithm, hashAlgorithm, hashedData, unhashedData, fingerprint, signature)
        {
        }

		/**
        * Generate a version 2/3 signature packet.
        *
        * @param signatureType
        * @param keyAlgorithm
        * @param hashAlgorithm
        * @param fingerprint
        * @param signature
        */
        public SignaturePacket(
            int						version,
            int						signatureType,
            long					keyId,
            PublicKeyAlgorithmTag	keyAlgorithm,
            HashAlgorithmTag		hashAlgorithm,
            long					creationTime,
            byte[]					fingerprint,
            MPInteger[]				signature)
            : this(version, signatureType, keyId, keyAlgorithm, hashAlgorithm, null, null, fingerprint, signature)
        {
			this.creationTime = creationTime;
        }

		public SignaturePacket(
            int						version,
            int						signatureType,
            long					keyId,
            PublicKeyAlgorithmTag	keyAlgorithm,
            HashAlgorithmTag		hashAlgorithm,
            SignatureSubpacket[]	hashedData,
            SignatureSubpacket[]	unhashedData,
            byte[]					fingerprint,
            MPInteger[]				signature)
        {
            this.version = version;
            this.signatureType = signatureType;
            this.keyId = keyId;
            this.keyAlgorithm = keyAlgorithm;
            this.hashAlgorithm = hashAlgorithm;
            this.hashedData = hashedData;
            this.unhashedData = unhashedData;
            this.fingerprint = fingerprint;
            this.signature = signature;

			if (hashedData != null)
			{
				SetCreationTime();
			}
		}

		public int Version
        {
			get { return version; }
        }

		public int SignatureType
        {
			get { return signatureType; }
		}

		/**
        * return the keyId
        * @return the keyId that created the signature.
        */
        public long KeyId
        {
            get { return keyId; }
        }

		/**
        * return the signature trailer that must be included with the data
        * to reconstruct the signature
        *
        * @return byte[]
        */
        public byte[] GetSignatureTrailer()
        {
			if (version == 3)
            {
                long time = creationTime / 1000L;

                byte[] trailer = new byte[5];
				trailer[0] = (byte)signatureType;
                trailer[1] = (byte)(time >> 24);
                trailer[2] = (byte)(time >> 16);
                trailer[3] = (byte)(time >>  8);
                trailer[4] = (byte)(time      );
                return trailer;
            }

            MemoryStream sOut = new MemoryStream();

			sOut.WriteByte((byte)Version);
            sOut.WriteByte((byte)SignatureType);
            sOut.WriteByte((byte)KeyAlgorithm);
            sOut.WriteByte((byte)HashAlgorithm);

            // Mark position an reserve two bytes for length
            long lengthPosition = sOut.Position;
            sOut.WriteByte(0x00);
            sOut.WriteByte(0x00);

            SignatureSubpacket[] hashed = GetHashedSubPackets();
			for (int i = 0; i != hashed.Length; i++)
            {
                hashed[i].Encode(sOut);
            }

            ushort dataLength = Convert.ToUInt16(sOut.Position - lengthPosition - 2);
            uint hDataLength = Convert.ToUInt32(sOut.Position);

			sOut.WriteByte((byte)Version);
            sOut.WriteByte(0xff);
            sOut.WriteByte((byte)(hDataLength >> 24));
            sOut.WriteByte((byte)(hDataLength >> 16));
            sOut.WriteByte((byte)(hDataLength >>  8));
            sOut.WriteByte((byte)(hDataLength      ));

            // Reset position and fill in length
            sOut.Position = lengthPosition;
            sOut.WriteByte((byte)(dataLength >> 8));
            sOut.WriteByte((byte)(dataLength     ));

            return sOut.ToArray();
        }

		public PublicKeyAlgorithmTag KeyAlgorithm
        {
			get { return keyAlgorithm; }
        }

		public HashAlgorithmTag HashAlgorithm
		{
			get { return hashAlgorithm; }
        }

		/**
		* return the signature as a set of integers - note this is normalised to be the
        * ASN.1 encoding of what appears in the signature packet.
        */
        public MPInteger[] GetSignature()
        {
            return signature;
        }

		/**
		 * Return the byte encoding of the signature section.
		 * @return uninterpreted signature bytes.
		 */
		public byte[] GetSignatureBytes()
		{
			if (signatureEncoding != null)
			{
				return (byte[]) signatureEncoding.Clone();
			}

			MemoryStream bOut = new MemoryStream();
			BcpgOutputStream bcOut = new BcpgOutputStream(bOut);

			foreach (MPInteger sigObj in signature)
			{
				try
				{
					bcOut.WriteObject(sigObj);
				}
				catch (IOException e)
				{
					throw new Exception("internal error: " + e);
				}
			}

			return bOut.ToArray();
		}

		public SignatureSubpacket[] GetHashedSubPackets()
        {
            return hashedData;
        }

		public SignatureSubpacket[] GetUnhashedSubPackets()
        {
            return unhashedData;
        }

		/// <summary>Return the creation time in milliseconds since 1 Jan., 1970 UTC.</summary>
        public long CreationTime
        {
            get { return creationTime; }
        }

		public override void Encode(BcpgOutputStream bcpgOut)
        {
            MemoryStream bOut = new MemoryStream();
            using (var pOut = new BcpgOutputStream(bOut))
            {
                pOut.WriteByte((byte)version);

                if (version == 3 || version == 2)
                {
                    byte nextBlockLength = 5;
                    pOut.Write(nextBlockLength, (byte)signatureType);
                    pOut.WriteInt((int)(creationTime / 1000L));
                    pOut.WriteLong(keyId);
                    pOut.Write((byte)keyAlgorithm, (byte)hashAlgorithm);
                }
                else if (version == 4)
                {
                    pOut.Write((byte)signatureType, (byte)keyAlgorithm, (byte)hashAlgorithm);
                    EncodeLengthAndData(pOut, GetEncodedSubpackets(hashedData));
                    EncodeLengthAndData(pOut, GetEncodedSubpackets(unhashedData));
                }
                else
                {
                    throw new IOException("unknown version: " + version);
                }

                pOut.Write(fingerprint);

                if (signature != null)
                {
                    pOut.WriteObjects(signature);
                }
                else
                {
                    pOut.Write(signatureEncoding);
                }
            }

			bcpgOut.WritePacket(PacketTag.Signature, bOut.ToArray(), true);
        }

		private static void EncodeLengthAndData(
			BcpgOutputStream	pOut,
			byte[]				data)
		{
			pOut.WriteShort((short) data.Length);
			pOut.Write(data);
		}

		private static byte[] GetEncodedSubpackets(
			SignatureSubpacket[] ps)
		{
			MemoryStream sOut = new MemoryStream();

			foreach (SignatureSubpacket p in ps)
			{
				p.Encode(sOut);
			}

			return sOut.ToArray();
		}

		private void SetCreationTime()
		{
			foreach (SignatureSubpacket p in hashedData)
			{
				if (p is SignatureCreationTime signatureCreationTime)
				{
                    creationTime = DateTimeUtilities.DateTimeToUnixMs(signatureCreationTime.GetTime());
					break;
				}
			}
		}

        public static SignaturePacket FromByteArray(byte[] data)
        {
            BcpgInputStream input = BcpgInputStream.Wrap(new MemoryStream(data));

            return new SignaturePacket(input);
        }
    }
}