Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# System.Security.Cryptography - why specify key and IV twice?

Most of the examples that show how to encrypt using the AES code in System.Security.Cryptography look like this:

using (Aes aes = Aes.Create())
{
   aes.Key = Key;
   aes.IV = IV;
   ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

Is it necessary to specify the key and IV twice - once to the Aes object and once to the CreateEncryptor() function? Or in this case, since I've already specified the key and IV, can I call the form of CreateEncryptor() that takes no arguments?

like image 954
Betty Crokker Avatar asked Jan 20 '26 15:01

Betty Crokker


1 Answers

You don't have to. You can use the CreateEncryptor() overload (without parameters), if you used the properties to specify the values:

public virtual ICryptoTransform CreateEncryptor() {
    return CreateEncryptor(Key, IV);
}

Here's what the doc says:

Creates a symmetric encryptor object with the current Key property and initialization vector (IV).

Or you can omit setting the properties and use the overload with arguments if you don't use the aes object afterwards to create other encryptors/decryptors.

like image 120
Lucas Trzesniewski Avatar answered Jan 22 '26 03:01

Lucas Trzesniewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!