summary refs log tree commit diff
path: root/crypto/src/crypto/tls/TlsDHUtilities.cs
blob: 733749ea14cd25a597b65d0e5b1040ae8849ea2c (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
using System;
using System.IO;

using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Crypto.Tls
{
	public abstract class TlsDHUtilities
	{
		public static byte[] CalculateDHBasicAgreement(DHPublicKeyParameters publicKey,
			DHPrivateKeyParameters privateKey)
		{
			DHBasicAgreement dhAgree = new DHBasicAgreement();
			dhAgree.Init(privateKey);
			BigInteger agreement = dhAgree.CalculateAgreement(publicKey);
			return BigIntegers.AsUnsignedByteArray(agreement);
		}

		public static AsymmetricCipherKeyPair GenerateDHKeyPair(SecureRandom random, DHParameters dhParams)
		{
			DHBasicKeyPairGenerator dhGen = new DHBasicKeyPairGenerator();
			dhGen.Init(new DHKeyGenerationParameters(random, dhParams));
			return dhGen.GenerateKeyPair();
		}

		public static DHPrivateKeyParameters GenerateEphemeralClientKeyExchange(SecureRandom random,
			DHParameters dhParams, Stream output)
		{
			AsymmetricCipherKeyPair dhAgreeClientKeyPair = GenerateDHKeyPair(random, dhParams);
			DHPrivateKeyParameters dhAgreeClientPrivateKey =
				(DHPrivateKeyParameters)dhAgreeClientKeyPair.Private;

			BigInteger Yc = ((DHPublicKeyParameters)dhAgreeClientKeyPair.Public).Y;
			byte[] keData = BigIntegers.AsUnsignedByteArray(Yc);
			TlsUtilities.WriteOpaque16(keData, output);

			return dhAgreeClientPrivateKey;
		}
		
		public static DHPublicKeyParameters ValidateDHPublicKey(DHPublicKeyParameters key)
		{
			BigInteger Y = key.Y;
			DHParameters parameters = key.Parameters;
			BigInteger p = parameters.P;
			BigInteger g = parameters.G;

			if (!p.IsProbablePrime(2))
			{
				throw new TlsFatalAlert(AlertDescription.illegal_parameter);
			}
			if (g.CompareTo(BigInteger.Two) < 0 || g.CompareTo(p.Subtract(BigInteger.Two)) > 0)
			{
				throw new TlsFatalAlert(AlertDescription.illegal_parameter);
			}
			if (Y.CompareTo(BigInteger.Two) < 0 || Y.CompareTo(p.Subtract(BigInteger.One)) > 0)
			{
				throw new TlsFatalAlert(AlertDescription.illegal_parameter);
			}

			// TODO See RFC 2631 for more discussion of Diffie-Hellman validation

			return key;
		}
	}
}