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

1

6
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?

Balch answered 8/2, 2012 at 13:33 Comment(0)
F
5

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.

Frisbie answered 8/2, 2012 at 13:38 Comment(3)
Thank you very much for explaining that along with such a quick reply. I didn't get an email telling me that you had answered my question, thus my delay in coming back. I retested my code with increased (but not total) confidence that the apparent randomness wouldn’t cause a problem and it didn’t. On decrypting, I suppose that the salt must be extracted from the encrypted bytes.Balch
The salt is handled by the crypto provider. All you do is call Encrypt and Decrypt.Frisbie
It's not called a salt in cryptographic terms, Tomislav. Most of the time it is referred to as "random padding". Salts are typically used for password based key derivation functions (aka password hashing).Chuckwalla

© 2022 - 2024 — McMap. All rights reserved.