summaryrefslogtreecommitdiffstats
path: root/src/DotNetOpenId.Test/DiffieHellmanUtilTests.cs
blob: 9b2fba9bb62271ba1193586c8d63c58758d5a654 (plain)
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.Collections.Generic;
using System.Text;
using System.IO;
using Org.Mentalis.Security.Cryptography;
using NUnit.Framework;

namespace DotNetOpenId.Test {
	public static class DHTestUtil {
		public static string Test1() {
			DiffieHellman dh1 = DiffieHellmanUtil.CreateDiffieHellman();
			DiffieHellman dh2 = DiffieHellmanUtil.CreateDiffieHellman();

			string secret1 = Convert.ToBase64String(dh1.DecryptKeyExchange(dh2.CreateKeyExchange()));
			string secret2 = Convert.ToBase64String(dh2.DecryptKeyExchange(dh1.CreateKeyExchange()));

			Assert.AreEqual(secret1, secret2, "Secret keys do not match for some reason.");

			return secret1;
		}
	}

	[TestFixture]
	public class DiffieHellmanUtilTests {

		[Test]
		public void Test() {
			string s1 = DHTestUtil.Test1();
			string s2 = DHTestUtil.Test1();

			Assert.AreNotEqual(s1, s2, "Secret keys should NOT be the same.");
		}

		[Test, Explicit("Test is slow.")]
		public void TestPublic() {
			StreamReader sr = new StreamReader(@"..\..\src\DotNetOpenId.Test\dhpriv.txt");

			try {
				string line;
				while ((line = sr.ReadLine()) != null) {
					string[] parts = line.Trim().Split(' ');
					byte[] x = Convert.FromBase64String(parts[0]);
					DiffieHellmanManaged dh = new DiffieHellmanManaged(DiffieHellmanUtil.DEFAULT_MOD, DiffieHellmanUtil.DEFAULT_GEN, x);
					byte[] pub = dh.CreateKeyExchange();
					byte[] y = Convert.FromBase64String(parts[1]);

					if (y[0] == 0 && y[1] <= 127)
						y.CopyTo(y, 1);

					Assert.AreEqual(y, Convert.FromBase64String(DiffieHellmanUtil.UnsignedToBase64(pub)), line);
				}
			} finally {
				sr.Close();
			}
		}

	}

}