I am using AES encryption in my application to encrypt user PATs (Personal Access Tokens) before storing them in the database. The primary goal of this encryption is to prevent anyone with database access from seeing the actual PAT values.
I am considering using the same Initialization Vector (IV) for all PAT encryption operations. The encrypted values will not be exposed to the frontend; the encryption is solely to protect the data at rest in the database.
- Is using the same IV for all PAT encryption operations a bad idea?
- Would it be better to use a random IV for each encryption and
prepend it to the generated ciphertext?
Here is the code I am using to generate cypher text. _key is stored in keyvault.
string EncryptText(string plaintext)
{
byte[] array;
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(_key);
aes.GenerateIV();
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(aes.IV, 0, aes.IV.Length); // Prepend IV
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
{
streamWriter.Write(plaintext);
}
array = memoryStream.ToArray();
}
}
}
return Convert.ToBase64String(array);
}
Any insights or best practices for this scenario would be greatly appreciated.
1