public static List <BigInt> Encode() { Console.Write("Enter first prime number:"); var p = new BigInt(Console.ReadLine()); Console.Write("Enter second prime number:"); var q = new BigInt(Console.ReadLine()); var module = p * q; Console.Write($"Your module:{module}\n"); var fi = (p - new BigInt(1)) * (q - new BigInt(1)); Console.Write($"Your fi:{fi}\n"); var publicExp = CalculatePublicExponent(fi); Console.Write($"Your public exp:{publicExp}\n"); var privateExp = CalculatePrivateExponent(publicExp, fi); Console.Write($"Your private exponent:{privateExp}\n"); Console.Write("Enter your message:"); var message = Encoding.ASCII .GetBytes(Console.ReadLine() ?? string.Empty) .Select(x => (int)x) .ToArray(); var encodedMsg = new List <BigInt>(); Console.Write($"Your encoded message:\n"); foreach (var code in message) { if (new BigInt(code.ToString()) > module) { throw new Exception("Module is too small - use bigger prime numbers"); } var encodedLetter = BigInt.ModPow(new BigInt(code.ToString()), publicExp, module); encodedMsg.Add(encodedLetter); Console.Write(encodedLetter + " "); } Console.WriteLine(); return(encodedMsg); }
public static string Decode() { Console.Write("Enter your module:"); var module = new BigInt(Console.ReadLine()); Console.Write("Enter your private exponent:"); var privateExp = new BigInt(Console.ReadLine()); Console.Write("Enter your encoded message:"); var encodedMsg = Console.ReadLine().Split(' '); var decodedLetters = new List <int>(); foreach (var code in encodedMsg) { var decodedLetter = BigInt.ModPow(new BigInt(code.ToString()), privateExp, module); decodedLetters.Add(int.Parse(decodedLetter.ToString())); } var decodedMsg = Encoding.ASCII.GetString(decodedLetters.Select(x => (byte)x).ToArray()); Console.WriteLine($"Decoded message:{decodedMsg}"); return(decodedMsg); }
public void CorrectDecode(string value, string number1, string number2) { var p = new BigInt(number1); var q = new BigInt(number2); var module = p * q; var phi = (p - new BigInt(1)) * (q - new BigInt(1)); var publicExp = RSA.CalculatePublicExponent(phi); var privateExp = RSA.CalculatePrivateExponent(publicExp, phi); var message = Encoding.ASCII .GetBytes(value) .Select(x => (int)x) .ToArray(); var encodedMsg = new List <BigInt>(); foreach (var code in message) { if (new BigInt(code.ToString()) > module) { throw new Exception("Module is too small - use bigger prime numbers"); } var encodedLetter = BigInt.ModPow(new BigInt(code.ToString()), publicExp, module); encodedMsg.Add(encodedLetter); Console.Write(encodedLetter + " "); } var decodedLetters = new List <int>(); foreach (var code in encodedMsg) { var decodedLetter = BigInt.ModPow(new BigInt(code.ToString()), privateExp, module); decodedLetters.Add(int.Parse(decodedLetter.ToString())); } var decodedMsg = Encoding.ASCII.GetString(decodedLetters.Select(x => (byte)x).ToArray()); CollectionAssert.AreEqual(decodedMsg, message); }