Skip to content

Instantly share code, notes, and snippets.

@quangnle
Created May 12, 2016 08:56
Show Gist options
  • Save quangnle/f1bb57b36c81d77cf451923181721fdf to your computer and use it in GitHub Desktop.
Save quangnle/f1bb57b36c81d77cf451923181721fdf to your computer and use it in GitHub Desktop.
public class RSA
{
private int _n;
private int _e;
private int _d;
private int _phi;
public RSA(int p, int q)
{
_n = p * q;
_phi = (p - 1) * (q - 1);
_e = FindE(_phi);
if (_e > 0)
{
_d = FindD(_e, _phi);
if (_d < 0) throw new Exception("input is not allowed");
} else
if (_d < 0) throw new Exception("input is not allowed");
}
public byte[] Encrypt(byte[] st)
{
byte[] m = new byte[st.Length];
for (int i = 0; i < st.Length; i++)
{
m[i] = (byte)PowerMod(st[i], _e, _n);
}
return m;
}
public byte[] Decrypt(byte[] st)
{
byte[] m = new byte[st.Length];
for (int i = 0; i < st.Length; i++)
{
m[i] = (byte)PowerMod(st[i], _d, _n);
}
return m;
}
private int PowerMod(byte n, int exp, int m)
{
if (exp == 0) return 1;
int r = 1;
for (int i = 0; i < exp; i++)
{
r = (r * n) % m;
}
return r;
}
private int FindE(int n)
{
for (int i = n - 1; i > 1; i--)
{
if (Gcd(n, i) == 1) return i;
}
return -1;
}
public int FindD(int e, int phi)
{
for (int i = 1; i < phi; i++)
{
if ((i * e) % phi == 1) return i;
}
return -1;
}
private int Gcd(int a, int b)
{
while (a != 0)
{
var tmp = a;
a = a % b;
b = tmp;
}
return b;
}
}
class Program
{
static void Main(string[] args)
{
string st = "Attack at dawn";
RSA rsa = new RSA(11, 13);
var m = st.ToList().Select(c => (byte)c).ToArray();
Console.WriteLine("Source message:");
for (int i = 0; i < m.Length; i++)
{
Console.Write("{0:D3} ", m[i]);
}
Console.WriteLine();
Console.WriteLine("Encrypted message:");
m = rsa.Encrypt(m);
for (int i = 0; i < m.Length; i++)
{
Console.Write("{0:D3} ", m[i]);
}
Console.WriteLine();
Console.WriteLine("Decrypted message:");
m = rsa.Decrypt(m);
for (int i = 0; i < m.Length; i++)
{
Console.Write("{0:D3} ", m[i]);
}
Console.Read();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment