Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypting data using RSACryptoServiceProvider has what seems to me as a bizarre feature

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?

like image 968
Arieh Avatar asked Feb 08 '12 13:02

Arieh


1 Answers

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.

like image 96
Tomislav Markovski Avatar answered Nov 05 '22 20:11

Tomislav Markovski