在C#中对RSA进行RSA加密并在openSSL中对其进行解密会使消息过长

时间:2016-05-20 06:59:21

标签: c# encryption rsa

我正在使用RSA加密C#中的字符串。在python中完成相同的存根工作,但是当使用C#加密它时,我在解密说“消息太大”时遇到问题。

    public static string RSAEncryptMessage(string msg)
    {
        var publicKeystr =
        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp+mrzAmFuuX1o2PZLA3C" +
        "/X3c4BTiHbjhR2mF8N5fha5WuiwxNJHtXbJXka4euzhnEdgp4+9zpc7mplgLAMDa" +
        "+BGKE7bjNrUmrckX2Aaaf+G1O1w1iU40+cTUm0NfZ6K0v4sLCpzqTnvjw5ilvliL" +
        "B5+6vHxvKMHlS6l/tdHgbelv1e7fZZeOVPczS5TDfTkJqMFIoI4KzzcH6Izsxu+H" +
        "EizWrT5zYkOCNLWQIpwcMq3h0EXc/qw7NAg/BRMg6HHVkbMNm3eTVzjDq3o77YKq" +
        "NHo2Plt2U9DeT5WcsEIslL7SjNV8ib0KVHMBaVQFu+5emsI3dn3VWEV5ZPkBngX2" +
        "NQIDAQAB";


        byte[] pubkeybytes = Convert.FromBase64String(publicKeystr);
        System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
        System.Security.Cryptography.RSAParameters rsaParam = rsa.ExportParameters(false);
        rsaParam.Modulus = pubkeybytes;
        rsa.ImportParameters(rsaParam);
        byte[] bytemsg = Encoding.ASCII.GetBytes(msg);
        Console.WriteLine(bytemsg.Length);
        byte[] encValue = rsa.Encrypt(bytemsg, false);
        Console.WriteLine(encValue.Length);
        return Convert.ToBase64String(encValue);



    }

我正在加密的邮件是:

public static void Main()
{

    Console.WriteLine(RSAEncryptMessage("1234"));
    Console.ReadLine();

}

生成的密文大小为294字节。使用openSSL加密的相同密文大小只有256个字节。什么是C#正在导致长度增加?这是一种不同类型的填充物吗?

1 个答案:

答案 0 :(得分:1)

您的publicKeystr看起来是一个完整的公钥(模数和指数),但是您使用它来设置rsaParam.Modulus

您需要从公钥中提取模数和指数,然后使用它们分别设置rsaParam.ModulusrsaParam.Exponent,或更改代码以便能够处理完整的公开键。

如果您按如下方式设置模数,它应该能满足您的期望。这里的模数和指数只是从原始publicKeystr中提取的值。

var modulus =
    "p+mrzAmFuuX1o2PZLA3C/X3c4BTiHbjhR2mF8N5fha5WuiwxNJHtXbJXka4euzhn" +
    "Edgp4+9zpc7mplgLAMDa+BGKE7bjNrUmrckX2Aaaf+G1O1w1iU40+cTUm0NfZ6K0" +
    "v4sLCpzqTnvjw5ilvliLB5+6vHxvKMHlS6l/tdHgbelv1e7fZZeOVPczS5TDfTkJ" +
    "qMFIoI4KzzcH6Izsxu+HEizWrT5zYkOCNLWQIpwcMq3h0EXc/qw7NAg/BRMg6HHV" +
    "kbMNm3eTVzjDq3o77YKqNHo2Plt2U9DeT5WcsEIslL7SjNV8ib0KVHMBaVQFu+5e" +
    "msI3dn3VWEV5ZPkBngX2NQ==";
var exponent = "AQAB";

rsaParam.Modulus = Convert.FromBase64String(modulus);
rsaParam.Exponent = Convert.FromBase64String(exponent);