[英]Successfully RSA Encrypting data in C#
我正在尝试在我的 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);
其他信息:
我错过了什么/做错了什么?
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 十六进制(65537 或费马的第五个质数,称为 F4)。
RSA的CNG 实现似乎更灵活,因此如果您想测试 RSA 的某些细节,也可以尝试这样做。
但是,最终您需要使用 RSA 密钥对生成程序来创建有效的 RSA 密钥对; 没有其他东西是安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.