【问题标题】:Encryption with certificate使用证书加密
【发布时间】:2012-11-24 20:14:21
【问题描述】:

我对所有这些加密事情都很陌生,我正在尝试做一个简单的应用程序来加密给定的字符串。这是我的代码:

public static X509Certificate2 getPublicKey()
{
    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

    X509Certificate2 cert2 = new X509Certificate2("c:\\certificate.cer");

    return cert2;
}


public static string cipherRequest(byte[] stringToEncrypt)
{
    X509Certificate2 certificate = getPublicKey();

    RSACryptoServiceProvider rsa = certificate.PublicKey.Key as RSACryptoServiceProvider;

    byte[] cryptedData = rsa.Encrypt(stringToEncrypt, true);

    return Convert.ToBase64String(cryptedData);
}

public static void Main()
{

    try
    {

        ASCIIEncoding ByteConverter = new ASCIIEncoding();

        byte[] test = ByteConverter.GetBytes("stringtoencrypt");

        string first = cipherRequest(test);
        string second= cipherRequest(test);

        Console.WriteLine("first: {0}", first);
        Console.WriteLine("second: {0}", second);

    }
    catch(CryptographicException e)
    {
        Console.WriteLine(e.Message);
    }

}

所以每次我调用cipherRequest 都会产生不同的结果。我已经检查过证书是否已加载,但它会产生不同的结果。

有什么想法吗?

【问题讨论】:

  • 此行为是设计使然。有实际问题吗?
  • 你为什么有一个byte[]命名的字符串?

标签: c# certificate public-key-encryption


【解决方案1】:

在实际加密之前添加随机填充以避免某些攻击。这就是为什么每次调用加密方法都会得到不同结果的原因。

有关更多信息,请参阅此帖子:

RSA in C# does not produce same encrypted string for specific keys?

【讨论】:

  • 谢谢,通过更多阅读,我终于得出了这个结论:)我的错
猜你喜欢
  • 2012-05-16
  • 2017-05-26
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多