我需要在C#中实现简单的RSA程序,它将加密和解密字符串(我只找到了整数而不是字符串的工作示例)。这就是我所拥有的:
public static BigInteger euklides(BigInteger e, BigInteger phi)
{
BigInteger x = BigInteger.Zero;
BigInteger y = BigInteger.One;
BigInteger lastx = BigInteger.One;
BigInteger lasty = BigInteger.Zero;
BigInteger temp;
BigInteger phiOriginal = phi;
while (!phi.Equals(BigInteger.Zero))
{
BigInteger q = BigInteger.Divide(e, phi);
BigInteger r = e % phi;
e = phi;
phi = r;
temp = x;
x = BigInteger.Subtract(lastx, BigInteger.Multiply(q, x));
lastx = temp;
temp = y;
y = BigInteger.Subtract(lasty, BigInteger.Multiply(q, y));
lasty = temp;
}
if (lastx.CompareTo(BigInteger.Zero) > 0)
return lastx;
else
return BigInteger.Subtract(phiOriginal, BigInteger.Negate(lastx));
}
static void Main(string[] args)
{
string p = "7980724731397402975742029729905308770673214017611336839039040369204140805514764089662732987804985392082433047940750616286743290036112256089536100737587703";
string q = "11740715087896814955393784459915361965809210593358905908497824655235476226804879681331854108325808626683143689269719764318983014066100961329905775841321093";
//Convert string to BigInteger
BigInteger rsa_p = BigInteger.Parse(p);
BigInteger rsa_q = BigInteger.Parse(q);
BigInteger rsa_n = BigInteger.Multiply(rsa_p, rsa_q);
BigInteger rsa_fn = BigInteger.Multiply((rsa_p - 1), (rsa_q - 1));
BigInteger rsa_e = 13;
BigInteger rsa_d = euklides(rsa_e, rsa_fn);
string message = "hellojs";
byte[] buffer2 = Encoding.ASCII.GetBytes(message);
BigInteger m = new BigInteger(buffer2);
BigInteger C = BigInteger.ModPow(m, rsa_e, rsa_n);
Console.WriteLine("Encrypted: " + Convert.ToBase64String(C.ToByteArray()));
BigInteger M = BigInteger.ModPow(C, rsa_d, rsa_n);
byte[] decoded2 = M.ToByteArray();
if (decoded2[0] == 0)
{
decoded2 = decoded2.Where(b => b != 0).ToArray();
}
string message3 = ASCIIEncoding.ASCII.GetString(decoded2);
Console.WriteLine("Decrypted: " + message3);
Console.ReadKey();
}
我的问题是解密 - 我得到一些随机不可读的字符。在加密之前将字符串转换为BigInteger并且在解密之后将BigInteger转换为字符串似乎有问题。有谁知道如何解决它?谢谢:))
编辑:
对于硬编码的值,程序不起作用。但对于另一个值,如: p 895493730028043880424493947156310024783769570419237367312822281990143938858343133550073770770223036789276483743805430421717817291115136285741935009393873829
q 11326960495280396859963951277476202902476795535605385467047045654941363025487995731611833231534039530362375614741751500907989679189162164468639573092827123
它现在正在运作。我不明白为什么:)