【问题标题】:Successfully RSA Encrypting data in C#在 C# 中成功 RSA 加密数据
【发布时间】:2023-04-07 00:36:01
【问题描述】:

我正在尝试在我的 C# 程序中实现 RSA 加密

这是我的代码:

using System;
using System.Security.Cryptography;

string dataToEncrypt = "Data to Encrypt here";
string modulus= "Public Key here";
string exponent= "Public Key Kxpiry here";

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

RSAParameters RSAKeyInfo = new RSAParameters();

RSAKeyInfo.Modulus = Encoding.UTF8.GetBytes(modulus);
RSAKeyInfo.D = Encoding.UTF8.GetBytes(dataToEncrypt);
RSAKeyInfo.Exponent = Encoding.UTF8.GetBytes(exponent);

RSA.ImportParameters(RSAKeyInfo);

我收到此错误代码:

System.Security.Cryptography.CryptographicException: 'Bad Data.'

这一行给出了错误:RSA.ImportParameters(RSAKeyInfo);

其他信息:

  • Visual Studio 2019
  • Windows 窗体应用程序(.NET 框架)
  • 操作系统:Windows 10 专业版

我错过了什么/做错了什么?

【问题讨论】:

  • RSAKeyInfo.D = Encoding.UTF8.GetBytes(dataToEncrypt);。好吧,这没有意义,现在是吗? dataToEncrypt 不会去那里。你可以试试RSA 类的Encrypt() 方法。

标签: c# encryption rsa


【解决方案1】:

RSA 密钥生成是一个非常具体的过程,它依赖于或两个(或更多)质数。您不能只为 RSA 选择随机值以确保安全。再说一遍,RSA 在加密过程中依赖于模幂运算,这可能仍然“有效”,即生成不安全的答案。

但是,CSP(加密服务提供商)可能会带来额外的限制。例如,Microsoft CSP 对密钥大小有以下限制:

Windows CSP 为 Windows 8.1 之前的 Windows 版本启用 384 到 16384 位的密钥大小,为 Windows 8.1 启用 512 到 16384 位的密钥大小。

因为密钥大小被指定为模数的大小。此外,密钥大小也必须是 8 的倍数。这意味着字节数组中的最高有效位必须设置为 1,而 UTF-8 绝不是这种情况。

此外,公共指数也可能受到限制;对于 Windows CSP,它需要小于 32 位。一般来说,它只是简单地设置为值 010001 hex(65537 或 Fermat 的第五个素数,称为 F4)。


CNG implentation of RSA 似乎更灵活,因此如果您想测试 RSA 的某些细节,也可以尝试一下。

但是,最终您需要使用 RSA 密钥对生成程序来创建有效的 RSA 密钥对;没有什么是安全的。

【讨论】:

    猜你喜欢
    • 2018-05-21
    • 2012-01-15
    • 1970-01-01
    • 2015-03-16
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多