AsymmetricAlgorithm.KeySize Property

Definition

Gets or sets the size, in bits, of the key modulus used by the asymmetric algorithm.

C#
public virtual int KeySize { get; set; }

Property Value

The size, in bits, of the key modulus used by the asymmetric algorithm.

Exceptions

The key modulus size is invalid.

Examples

The following code example demonstrates how to override the KeySize property to verify that it falls within the range identified in the local keySizes member variable. This code example is part of a larger example provided for the AsymmetricAlgorithm class.

C#
public override int KeySize 
{
    get { return KeySizeValue; }
    set
    {
        for (int i=0; i < keySizes.Length; i++)
        {
            if (keySizes[i].SkipSize == 0) 
            {
                if (keySizes[i].MinSize == value)
                {
                    KeySizeValue = value;
                    return;
                }
            }
            else
            {
                for (int j = keySizes[i].MinSize;
                    j <= keySizes[i].MaxSize;
                    j += keySizes[i].SkipSize)
                {
                    if (j == value)
                    {
                        KeySizeValue = value;
                        return;
                    }
                }
            }
        }

        // If the key does not fall within the range identified 
        // in the keySizes member variable, throw an exception.
        throw new CryptographicException("Invalid key size.");
    }
}

Remarks

The valid key sizes are specified by the particular implementation of the asymmetric algorithm and are listed in the LegalKeySizes property.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

See also