summaryrefslogtreecommitdiffstats
path: root/source/OpenIdTests/DiffieHellmanTestSuite.cs
blob: 0924fc6034e60f88b46f2a17779b2adfb7b7d516 (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
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Org.Mentalis.Security.Cryptography;
using NUnit.Framework;
using Janrain.OpenId;

namespace OpenIdTests
{
    public static class DHTestUtil
    {
        public static string Test1()
        {
            DiffieHellman dh1 = CryptUtil.CreateDiffieHellman();
            DiffieHellman dh2 = CryptUtil.CreateDiffieHellman();

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

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

            return secret1;
        }
    }

    [TestFixture]
    public class DiffieHellmanTestSuite
    {

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

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

        [Test]
        public void TestPublic()
        {
            StreamReader sr = new StreamReader("..\\..\\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(CryptUtil.DEFAULT_MOD, CryptUtil.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(CryptUtil.UnsignedToBase64(pub)), line);
                }
            }
            finally
            {
                sr.Close();
            }
        }

    }

}