All rules
CA5402Security Enabled by default: No

Use CreateEncryptor with the default IV

Use CreateEncryptor with the default IV

Microsoft docs

Description

Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks.

This rule is similar to CA5401, but analysis can't determine that the initialization vector is definitely the default.

Cause

The rgbIV could be non-default when using System.Security.Cryptography.SymmetricAlgorithm.CreateEncryptor.

How to fix violations

Use the default rgbIV value explicitly, that is, use the overload of the System.Security.Cryptography.SymmetricAlgorithm.CreateEncryptor which doesn't have any parameter.

Example

using System;
using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod(byte[] rgbIV)
    {
        AesCng aesCng  = new AesCng();
        Random r = new Random();

        if (r.Next(6) == 4)
        {
            aesCng.IV = rgbIV;
        }

        aesCng.CreateEncryptor();
    }
}

using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod()
    {
        AesCng aesCng  = new AesCng();
        aesCng.CreateEncryptor();
    }
}

When to suppress

It's safe to suppress a warning from this rule if:

  • The rgbIV parameter was generated by System.Security.Cryptography.SymmetricAlgorithm.GenerateIV.
  • You're sure that the rgbIV parameter is really random and non-repeatable.
  • You're sure that the initialization vector is used.
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0