我正在编写一个程序来使用从该网站生成的私钥和公钥进行加密和解密 - rsa_key_generation
我将密钥大小设置为 512 和 base64。这是我的代码。
class Program
{
private static RSACryptoServiceProvider _rsaProvider = new RSACryptoServiceProvider();
static string p = "DYy2r60MEQJR2gyYmkuEQp7F8a2D=rOjd60tOR=FF8Z";
static string q = "8_oSxChqnGrGHTW0gt4CggZ2pOQZI8SR1uFWZIn4yRr";
static string mod = "1vg1y6ZmYtGILIVgbgezzwUcnnmSRp1hwQuxRTIiQNbrz=fi4myRn7KwJyG2aKDEG69pseLMqetYYCTQUKCyr=";
static string exp = "G01";
static string d = "1khYtBuSMaCtYf7ECrIV6=b36bBGwxUvzTUrwQvRJNf70h0sFNnxBARiNrZdb8DWJsgjQEKhBUcWOD4aII1xv1";
static string dP = "6VTNXCrpUJP_tbJbzCA_s38haB_T3IEGWYC_1pCpha=";
static string dQ = "3=p7GQ9v613wldg8eSEdxNCvRfeIfBvhomPdigmMwhP";
static void Main(string[] args)
{
string encryptedPIN = RSAEncrypt("1234");
Console.WriteLine("Encrypted Text Recieved: " + encryptedPIN);
string decryptedPIN = RSADecrypt(encryptedPIN);
Console.WriteLine("\nDecrypted Text Recieved: " + decryptedPIN);
Console.ReadLine();
}
public static string RSAEncrypt(string plainText)
{
AssingParams();
RSAParameters rsaParam = new RSAParameters();
rsaParam.Modulus = Encoding.UTF8.GetBytes(mod);
rsaParam.Exponent = Encoding.UTF8.GetBytes(exp);
_rsaProvider.ImportParameters(rsaParam);
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
byte[] cipherBytes = _rsaProvider.Encrypt(plainBytes, false);
return Convert.ToBase64String(cipherBytes);
}
public static string RSADecrypt(string cipherText)
{
AssingParams();
byte[] cipherBytes = Convert.FromBase64String(cipherText);
RSAParameters rsaParam = new RSAParameters();
rsaParam.Modulus = Encoding.UTF8.GetBytes(mod);
rsaParam.D = Encoding.UTF8.GetBytes(d);
rsaParam.Exponent = Encoding.UTF8.GetBytes(exp);
rsaParam.Q = Encoding.UTF8.GetBytes(q);
rsaParam.DP = Encoding.UTF8.GetBytes(dP);
rsaParam.DQ = Encoding.UTF8.GetBytes(dQ);
_rsaProvider.ImportParameters(rsaParam);
byte[] plainText = _rsaProvider.Decrypt(cipherBytes, false);
return Encoding.UTF8.GetString(plainText);
}
public static void AssingParams()
{
const int PROVIDER_RSA_FULL = 1;
const string CONTAINER_NAME = "RSAContainer";
CspParameters cspParams;
cspParams = new CspParameters(PROVIDER_RSA_FULL);
cspParams.KeyContainerName = CONTAINER_NAME;
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
_rsaProvider = new RSACryptoServiceProvider(1024, cspParams);
}
}
声明为字符串 p、q、mod、exp、d、dP 和 dQ 的变量是从网站上复制的。虽然加密在解密时工作正常,但我收到此错误“错误数据”。我尝试将模数添加到解密密钥然后我收到错误“密钥不存在”。
请帮忙。