[英]RSA Encryption and Decryption in C#.NET
I have below code to encrypt and decrypt the message in c#. 我有以下代码来加密和解密c#中的消息。 when i am trying to run it is giving an exception ie "The data to be decrypted exceeds the maximum for this modulus of 256 bytes" 当我尝试运行时,它给出了一个异常,即“要解密的数据超过了此最大模数的256字节”
public static void Main(string[] args)
{
X509Certificate2 cert = new X509Certificate2(@"C:\Data\ABC-rsa-public-key-certificate.cer");
string encryptedText = EncrypIt("Hello", cert);
string decryptedText = DecrptIt(encryptedText, cert);
System.Console.WriteLine(decryptedText);
}
public static string EncrypIt(string inputString, X509Certificate2 cert)
{
RSACryptoServiceProvider publicKey = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] plainBytes = Encoding.UTF8.GetBytes(inputString);
byte[] encryptedBytes = publicKey.Encrypt(plainBytes, false);
string encryptedText = Encoding.UTF8.GetString(encryptedBytes);
return encryptedText;
}
public static string DecrptIt(string encryptedText, X509Certificate2 cert)
{
RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] encryptedBytes = Encoding.UTF8.GetBytes(encryptedText);
byte[] decryptedBytes = privateKey.Decrypt(encryptedBytes, false);
string decryptedText = Encoding.UTF8.GetString(decryptedBytes);
return decryptedText;
}
Several problems: 几个问题:
RSA by default only encrypts one block. RSA默认情况下仅加密一个块。 It's not suitable for long messages. 它不适用于长消息。 You shouldn't encrypt the message itself with RSA. 您不应该使用RSA加密消息本身。 Generate a random AES key and encrypt the key with RSA and the actual message with AES. 生成随机AES密钥,并使用RSA加密密钥,并使用AES加密实际消息。
You must use a binary safe encoding such as Hex or Base64 for the ciphertext. 您必须对密文使用二进制安全编码,例如Hex或Base64。 Using UTF-8 corrupts the data since it doesn't allow arbitrary byte sequences. 使用UTF-8会破坏数据,因为它不允许任意字节序列。
UTF-8 is designed to encode text, so it's fine for your plaintext. UTF-8旨在对文本进行编码,因此适合您的纯文本。
Use OAEP, the old 1.5 padding mode is not secure. 使用OAEP,旧的1.5填充模式不安全。 ie pass true
as second parameter to Encrypt
/ Decrypt
. 即将true
作为第二个参数传递给Encrypt
/ Decrypt
。 (Technically it's possible to use it securely, but it's tricky and I wouldn't recommend it) (从技术上讲,可以安全地使用它,但这很棘手,我不推荐使用)
As a further note, once you use AES, there are some more pitfalls: 1) Use a MAC in an encrypt-then-mac scheme, else active attacks including padding-oracles will break your code 2) Use a random IV that's different for each message 进一步说明,一旦使用AES,就会有更多陷阱:1)在“加密-然后-MAC”方案中使用MAC,否则包括padding-oracles在内的主动攻击都会破坏您的代码2)使用不同的随机IV每条消息
RSA should not be used to encrypt this kind of data. RSA不应用于加密此类数据。 You should be encrypting your data with a symmetric key like AES, then encrypting the symmetric key with RSA. 您应该先使用AES等对称密钥加密数据,然后再使用RSA加密对称密钥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.