Rules / C#
SHIELD-CSHARP-012
Insecure ECB cipher mode
What it detects
A symmetric cipher is configured to use ECB mode, which leaks plaintext patterns.
How to fix
Use an authenticated mode such as GCM, or CBC with a random IV instead of ECB.
Vulnerable — Shield flags thisTokenCipher.cs
using System.Security.Cryptography;
public class TokenCipher
{
public byte[] Encrypt(byte[] plaintext, byte[] key)
{
using var aes = Aes.Create();
aes.Mode = CipherMode.ECB;
aes.Key = key;
using var encryptor = aes.CreateEncryptor();
return encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length);
}
}
Fixed — scans cleanTokenCipher.cs
using System.Security.Cryptography;
public class TokenCipher
{
public byte[] Encrypt(byte[] plaintext, byte[] key)
{
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.GenerateIV();
using var encryptor = aes.CreateEncryptor();
return encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length);
}
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CSHARP-012, the fixed one does not.