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

using Org.BouncyCastle.Math;

namespace Org.BouncyCastle.Bcpg
{
	/// <remarks>A multiple precision integer</remarks>
    public class MPInteger
        : BcpgObject
    {
        private readonly BigInteger val;

        public MPInteger(
            BcpgInputStream bcpgIn)
        {
			if (bcpgIn == null)
				throw new ArgumentNullException("bcpgIn");

			int length = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte();
            byte[] bytes = new byte[(length + 7) / 8];

            bcpgIn.ReadFully(bytes);

            this.val = new BigInteger(1, bytes);
        }

		public MPInteger(
            BigInteger val)
        {
			if (val == null)
				throw new ArgumentNullException("val");
			if (val.SignValue < 0)
				throw new ArgumentException("Values must be positive", "val");

			this.val = val;
        }

		public BigInteger Value
        {
            get { return val; }
        }

        public override void Encode(
            BcpgOutputStream bcpgOut)
        {
			bcpgOut.WriteShort((short) val.BitLength);
			bcpgOut.Write(val.ToByteArrayUnsigned());
        }

		internal static void Encode(
			BcpgOutputStream	bcpgOut,
			BigInteger			val)
		{
			bcpgOut.WriteShort((short) val.BitLength);
			bcpgOut.Write(val.ToByteArrayUnsigned());
		}
    }
}