using System;
using System.Linq;
using System.Numerics;
class Program
{
static void Main(string[] args)
{
// 选择一个小于100的质数作为p和q,以及自然数e和d使得ed ≡ 1 (mod (p-1) * (q-1))
int p = 17;
int q = 19;
int n = p * q;
int phi = (p - 1) * (q - 1);
int e = 7;
int d = FindModInverse(e, phi);
Console.WriteLine("公钥:(n={0}, e={1})", n, e);
Console.WriteLine("私钥:(n={0}, d={1})", n, d);
string plainText = "Hello, world!"; // 待加密的明文
BigInteger cipherText; // 存放加密后的密文
string decryptedText; // 存放解密后的明文
// 加密
cipherText = Encrypt(plainText, n, e);
// 解密
decryptedText = Decrypt(cipherText, n, d);
Console.WriteLine("明文:" + plainText);
Console.WriteLine("密文:" + cipherText);
Console.WriteLine("解密后的明文:" + decryptedText);
}
// RSA加密函数
static BigInteger Encrypt(string message, int n, int e)
{
return BigInteger.ModPow(IntFromString(message), e, n);
}
// RSA解密函数
static string Decrypt(BigInteger encryptedMessage, int n, int d)
{
return StringFromInt(BigInteger.ModPow(encryptedMessage, d, n));
}
// 将字符串转化为整数
static BigInteger IntFromString(string s)
{
return new BigInteger(s.Select(c => (int)c).ToArray());
}
// 将整数转化为字符串
static string StringFromInt(BigInteger n)
{
return new string(n.ToByteArray()
.Where(b => b != 0)
.Select(b => (char)b)
.ToArray());
}
// 扩展欧几里得算法求模反元素(即逆元)
static int FindModInverse(int a, int m)
{
int m0 = m, t, q;
int x0 = 0, x1 = 1;
if (m == 1)
return 0;
while (a > 1)
{
// q是商,t是余数,只用到了t。计算q和t。
q = a / m;
t = m;
// 更新m和a,同步更新x0和x1。
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
// 当循环结束后,a和m的最大公约数为1。此时x1即为所求。
if (x1 < 0)
x1 += m0;
return x1;
}
}
02-04
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交