public static void Main(string[] args)
Console.WriteLine("Test completed.");
public static void TestRsaMaths()
var euclidResult = RSAMaths.EuclidsAlgo(649 * 11212, 649 * 231212);
Console.WriteLine("The result of euclids algo with " + (649 * 11212) + " and " + (649 * 231212) + " was " + euclidResult);
var extendedResult = RSAMaths.ExtendedEuclidsAlgo(649 * 11231, 649 * 1232321);
Console.WriteLine("The result of extended euclids with " + (649 * 11231) + " and " + (649 * 1232321) + " was " + extendedResult);
var modExResult = RSAMaths.ModEx(243234, 423423, 32313);
Console.WriteLine("The result of modular exponentiation of " + (243234) + "^" + (423423) + " Mod(" + (32313) + ") is " + modExResult);
var weakPrimalityResult = RSAMaths.WeakPrimality(561);
Console.WriteLine("The result of a weak primality test on " + 561 + " found it could " + (weakPrimalityResult ? "be prime." : "not be prime."));
var strongPrimalityResult = RSAMaths.StrongPrimality(561);
Console.WriteLine("The result of a strong primality test on " + 561 + " found it could " + (strongPrimalityResult? "be prime." : "not be prime."));
public long d {get; set;}
public long x {get; set;}
public long y {get; set;}
public override string ToString()
return "(" + d + ", " + x + ", " + y + ")";
public Triple Set(long d, long x, long y)
public static class RSAMaths
public static long EuclidsAlgo(long a, long b)
return EuclidsAlgo(b, a % b);
public static Triple ExtendedEuclidsAlgo(long a, long b)
return new Triple{d = a, x = 1, y = 0};
var v = ExtendedEuclidsAlgo(b, a % b);
return v.Set(v.d, v.y, v.x - (v.y * (a / b)));
public static long ModEx(long a, long b, long n)
for(var i = Convert.ToString(b, 2).Length - 1; i >= 0; i--)
if((b & (0x1 << i)) == (0x1 << i))
public static bool StrongPrimality(long n)
if(n % 2 == 0 || n % 3 == 0)
if (n % i == 0 || n % (i + 2) == 0)
public static bool WeakPrimality(long n)
if (ModEx(2, n - 1, n) % n != 1)