-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRSAUnitTest.java
114 lines (94 loc) · 2.67 KB
/
RSAUnitTest.java
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
//By Caleb Martin
import java.util.ArrayList;
import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
public class RSAUnitTest
{
@Test
public void maxPowDivTest()
{
Assert.assertEquals(RSA.maxPowDiv(2, 256), 8);
}
@Test
public void modPowTest()
{
int p = RSA.rand.nextInt(RSA.MAX_PRIME);
int a = RSA.rand.nextInt(p);
int e = RSA.rand.nextInt(RSA.MIN_PRIME);
BigInteger t = BigInteger.valueOf(a);
t = t.modPow(BigInteger.valueOf(e), BigInteger.valueOf(p));
Assert.assertEquals(RSA.modPow(a, e, p), t.longValueExact());
}
@Test
public void GCDTest()
{
int a = RSA.rand.nextInt(RSA.MAX_PRIME)+2;
int b = RSA.rand.nextInt(a)+1;
BigInteger t = BigInteger.valueOf(a);
Assert.assertEquals(RSA.extendedGCD(a, b)[0], t.gcd(BigInteger.valueOf(b)).longValueExact());
}
@Test
public void extendedGCDTest()
{
int a = RSA.rand.nextInt(RSA.MAX_PRIME)+2;
int b = RSA.rand.nextInt(a)+1;
long[] eGCD = RSA.extendedGCD(a, b);
Assert.assertEquals(a*eGCD[1]+b*eGCD[2], eGCD[0]);
}
@Test
public void millerRabinPrime()
{
Assert.assertFalse(RSA.millerRabin(5));
}
@Test
public void millerRabinPrime2()
{
Assert.assertFalse(RSA.millerRabin(8675309));
}
@Test
public void millerRabinComposite()
{
Assert.assertTrue(RSA.millerRabin(4));
}
@Test
public void millerRabinComposite2()
{
Assert.assertTrue(RSA.millerRabin(1234525));
}
@Test
public void getPrimeTest()
{
int n = RSA.getPrime();
//Brute force all factors
ArrayList<Integer> factors = new ArrayList<>();
for(int i=1; i<=n; i++)
{
if(n%i == 0)
{
factors.add(i);
}
}
//Prime numbers have 2 factors: 1 and themselves
Assert.assertEquals(factors.size(), 2);
}
@Test
public void getDecryptTest()
{
int p = RSA.getPrime();
int q = RSA.getPrime();
long e = RSA.getEncrypt(p, q);
long d = RSA.getDecrypt(p, q, e);
Assert.assertEquals((d*e)%((p-1)*(q-1)), 1);
}
@Test
public void RSAEncryptionTest()
{
int p = RSA.getPrime();
int q = RSA.getPrime();
long e = RSA.getEncrypt(p, q);
long d = RSA.getDecrypt(p, q, e);
int m = 17;
Assert.assertEquals(RSA.modPow(RSA.modPow(m, e, p*q), d, p*q), m);
}
}