Do not hard-code encryption key
Do not hard-code encryption key
Microsoft docsDescription
For a symmetric algorithm to be successful, the secret key must be known only to the sender and the receiver. When a key is hard-coded, it is easily discovered. Even with compiled binaries, it is easy for malicious users to extract it. Once the private key is compromised, the cipher text can be decrypted directly and is not protected anymore.
Cause
The key parameter of the System.Security.Cryptography.AesCcm or System.Security.Cryptography.AesGcm constructor, System.Security.Cryptography.SymmetricAlgorithm.Key property, or the rgbKey parameter of the System.Security.Cryptography.SymmetricAlgorithm.CreateEncryptor or System.Security.Cryptography.SymmetricAlgorithm.CreateDecryptor method is hard-coded by one of the following:
- Byte array.
- System.Convert.FromBase64String.
- All the overloads of System.Text.Encoding.GetBytes.
By default, this rule analyzes the entire codebase, but this is configurable.
How to fix violations
- Consider redesigning your application to use a secure key management system, such as Azure Key Vault.
- Keep credentials and keys in a secure location separate from your source code.
Example
using System;
using System.Security.Cryptography;
class ExampleClass
{
public void ExampleMethod(byte[] someOtherBytesForIV)
{
byte[] rgbKey = new byte[] {1, 2, 3};
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
rijn.CreateEncryptor(rgbKey, someOtherBytesForIV);
}
}
using System;
using System.Security.Cryptography;
class ExampleClass
{
public void ExampleMethod(byte[] someOtherBytesForIV)
{
byte[] key = Convert.FromBase64String("AAAAAaazaoensuth");
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
rijn.CreateEncryptor(key, someOtherBytesForIV);
}
}
using System.Text;
using System.Security.Cryptography;
class ExampleClass
{
public void ExampleMethod(byte[] someOtherBytesForIV)
{
byte[] key = Encoding.ASCII.GetBytes("AAAAAaazaoensuth");
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
rijn.CreateEncryptor(key, someOtherBytesForIV);
}
}
using System.Text;
using System.Security.Cryptography;
class ExampleClass
{
public void ExampleMethod(char[] chars, byte[] someOtherBytesForIV)
{
byte[] key = Encoding.ASCII.GetBytes(chars);
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
rijn.CreateEncryptor(key, someOtherBytesForIV);
}
}When to suppress
Do not suppress a warning from this rule.