Search code examples
c#asp.net-coreencryptionaesdata-protection

IV used in Microsoft.AspNetCore.DataProtection with default encryption algo AES-256-CBC


I am using Microsoft.AspNetCore.DataProtection for encryption and decryption of my data with the default algorithm (AES-256-CBC). As per my finding, I understand that given the same IV and same plaintext this encryption results in the same cipherText again and again. I have a use case where I need to do a data lookup for a plainText which I might have encrypted earlier and stored in some DB. I don't have an option to fetch from db and decrypt the data to check for a match.

Code example,

public class MyClass 
{
    IDataProtector dataProtector;
    IMyStoreRepository externalStore;

    public MyClass(IDataProtectionProvider dataProtectionProvider, IMyStoreRepository externalStore) 
    {
       this.dataProtector = dataProtectionProvider.CreateProtector("somePurposeString");
       this.externalStore = externalStore;
    }

    public string GetOrAddValue(string someKey)
    {
        string encryptedKey = this.dataProtector.Protect(someKey); // encrypt the given key

        if (this.externalStore.KeyExists(encryptedKey) // look up in the external store
        {
            return this.externalStore.GetValue(encryptedKey); // return the value if match in external store
        }

       string someValue = "foo-bar-foo-bar"; 
       this.externalStore.Set(encryptedKey, someValue); // setting the value in the external store with encrypted key
       return someValue;
    }
}

I am injecting the data protection-related dependencies in Program.cs with most of the default configurations.

My question is:

  1. What's the IV used for encryption if I use it as per the above code.
  2. If I use it in the above manner, will it produce same cipherText for a given plainText. Given that the master key is constant across all the encryption and decryption.

Solution

  • As per these documents, each Encrypt call generates a separate key and a random initialization vector (IV) at least with the default settings i.e AES-256-CBC for payload protection and HMACSHA256 for authenticity. For this reason, we can't generate the same cipherText corresponding to a given plainText.