我正在测试RSA算法,只是为了尝试测试使用错误的私钥(D 参数)解密时发生了什么。
我正在使用带有默认构造函数(没有参数)的RSACryptoServiceProvider
。我加密一个字节数组,然后更改私钥。为此,我导出到RSAParameters
对象修改 D 参数,然后再次导入。然后我解密信息,结果是原始数据!!
所以在它是如何工作的方面,我应该缺少一些东西。这是代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using Apoyo;
namespace PruebaRSA
{
class Program
{
static void Main(string[] args)
{
Ayuda ayuda = new Ayuda();
byte[] datosOriginales = new byte[10];
byte[] datosCifrados;
byte[] datosDescifrados;
CrearArrayDatos(datosOriginales);
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider();
datosCifrados = rsaCSP.Encrypt(datosOriginales, false);
//--------------------------------------------------------------
//Decrypt with the original Private Key
datosDescifrados = rsaCSP.Decrypt(datosCifrados, false);
Console.WriteLine("Texto Cifrado:");
ayuda.WriteHex(datosCifrados, datosCifrados.Length);
Console.WriteLine("Texto Descifrado:");
ayuda.WriteHex(datosDescifrados, datosDescifrados.Length);
//Change the Private Key
RSAParameters rsaParameters = rsaCSP.ExportParameters(true);
byte[] newD = new byte[rsaParameters.D.Length];
CrearArrayDatos(newD);
rsaParameters.D = newD;
rsaCSP.ImportParameters(rsaParameters);
//Decrypt with the new Private Key
datosDescifrados = rsaCSP.Decrypt(datosCifrados, false);
Console.WriteLine("Texto Descifrado:");
ayuda.WriteHex(datosDescifrados, datosDescifrados.Length);
rsaParameters = rsaCSP.ExportParameters(true);
Console.WriteLine("Clave privada utilizada: ");
ayuda.WriteHex(rsaParameters.D, rsaParameters.D.Length);
//____________________________________________
Console.Write("Presionar Tecla");
Console.Read();
}
private static void CrearArrayDatos(byte[] datos)
{
for (byte i = 0; i < datos.Length; i++)
{
datos[i] = i;
}
}
}
}
RSAParameter包含其他参数,可用于使用中文余数定理加速RSA解密。以这种方式解密不需要 D。它只需要 Dp 和 Dq。因此,如果您更改这两个参数之一,那么我希望解密失败。
当然,为了获得良好的安全性,如果 .net 还提供一致性检查,以便可以检测到参数不一致的私钥,那就太好了。(不确定是否未实施此类一致性检查,或者我只是找不到它)。