通过RSA算法对值进行加解密
Encrypt and decrypt value by RSA algorithm
我编写了一个RSA加解密程序。对于某些数值,解密结果与原始值不匹配。
例如:
- 327: 解密不错
- 512:解密有问题
我使用BigInteger.ModPow()
进行加密和解密。
using System;
using System.Numerics;
namespace ExperimentsWithCryptographicAlgorithms
{
class Program
{
static void Main(string[] args)
{
BigInteger number = new BigInteger(327);
KeyPair keys = new KeyPair();
keys.OpenKey = new Key(new BigInteger(5), new BigInteger(493));
keys.SecurityKey = new Key(new BigInteger(269), new BigInteger(493));
BigInteger hash = Encrypt(number, keys.OpenKey);
if (Decrypt(hash, keys.SecurityKey) == number)
{
Console.WriteLine("Succesfully encrypted / decrypted!");
}
else
{
Console.WriteLine("Error in encryption or decryption!");
}
}
static BigInteger Encrypt(BigInteger encryptedValue, Key publicKey)
{
return BigInteger.ModPow(encryptedValue, publicKey.FirstPart, publicKey.SecondPart);
}
static BigInteger Decrypt(BigInteger decryptedValue, Key securityKey)
{
return BigInteger.ModPow(decryptedValue, securityKey.FirstPart, securityKey.SecondPart);
}
}
public struct Key
{
public BigInteger FirstPart { get; set; }
public BigInteger SecondPart { get; set; }
public Key(BigInteger fPart, BigInteger sPart)
{
FirstPart = fPart;
SecondPart = sPart;
}
}
public struct KeyPair
{
public Key OpenKey { get; set; }
public Key SecurityKey { get; set; }
}
}
我检查了你的算法,它适用于 -492 到 492 范围内的数字。这似乎是算法的物理限制,因为最后一个算术运算是 securityKey.SecondPart 的模数,这发生了成为 493.
我编写了一个RSA加解密程序。对于某些数值,解密结果与原始值不匹配。
例如:
- 327: 解密不错
- 512:解密有问题
我使用BigInteger.ModPow()
进行加密和解密。
using System;
using System.Numerics;
namespace ExperimentsWithCryptographicAlgorithms
{
class Program
{
static void Main(string[] args)
{
BigInteger number = new BigInteger(327);
KeyPair keys = new KeyPair();
keys.OpenKey = new Key(new BigInteger(5), new BigInteger(493));
keys.SecurityKey = new Key(new BigInteger(269), new BigInteger(493));
BigInteger hash = Encrypt(number, keys.OpenKey);
if (Decrypt(hash, keys.SecurityKey) == number)
{
Console.WriteLine("Succesfully encrypted / decrypted!");
}
else
{
Console.WriteLine("Error in encryption or decryption!");
}
}
static BigInteger Encrypt(BigInteger encryptedValue, Key publicKey)
{
return BigInteger.ModPow(encryptedValue, publicKey.FirstPart, publicKey.SecondPart);
}
static BigInteger Decrypt(BigInteger decryptedValue, Key securityKey)
{
return BigInteger.ModPow(decryptedValue, securityKey.FirstPart, securityKey.SecondPart);
}
}
public struct Key
{
public BigInteger FirstPart { get; set; }
public BigInteger SecondPart { get; set; }
public Key(BigInteger fPart, BigInteger sPart)
{
FirstPart = fPart;
SecondPart = sPart;
}
}
public struct KeyPair
{
public Key OpenKey { get; set; }
public Key SecurityKey { get; set; }
}
}
我检查了你的算法,它适用于 -492 到 492 范围内的数字。这似乎是算法的物理限制,因为最后一个算术运算是 securityKey.SecondPart 的模数,这发生了成为 493.