using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace EncryptionTest
{
class Program
{
static void Main(string[] args)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes("Test data");
string enc = Encrypt(dataToEncrypt);
}
static string Encrypt(byte[] data)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
RSACryptoServiceProvider encrypt = new RSACryptoServiceProvider();
byte[] encryptedData = encrypt.Encrypt(data, false); //Repeat this line
return ByteConverter.GetString(encryptedData);
}
}
}
I used 'Set Next Statement' to repeatedly execute the following statement, i.e without any other lines of code being executed.
byte[] encryptedData = encrypt.Encrypt(data, false);
I looked at the bytes in encryptedData and found that the bytes in encryptedData change each time. Surely this is wrong? If the public key hasn't changed and the data to be encrypted hasn't been changed then the 'encryptedData' bytes should not change either?
No, it is working as intended. The encrypted data changes every time because it uses a padding scheme that uses random octets to encrypt the plain text every time you call Encrypt. The only thing that matters is if Decrypt(Encrypt(data))
returns your original byte array data
.
RSA padding (OAEP or PKCS#1 v1.5 compatible padding) is required for RSA to be secure. The random part of the padding also makes sure that the ciphertext of returned when you encrypt the plain text multiple times are distinct. This is an important security requirement, an attacker should not be able to find information about the plain text just by looking for repetition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With