0
\$\begingroup\$

Is the below method a safe way of generating a random encryption key to be used with AES (SymmetricAlgorithm) in .NET?

It essentially piggybacks off of the Aes alg to create a random key, trimmed to the correct bit size.

    /// <summary>
    /// Defines AES key sizes.
    /// </summary>
    public enum KeySize
    {
        /// <summary>
        /// Key size of 128 bits.
        /// </summary>
        Aes128 = 128,

        /// <summary>
        /// Ket size of 192 bits.
        /// </summary>
        Aes192 = 192,

        /// <summary>
        /// Key size of 256 bits.
        /// </summary>
        Aes256 = 256
    }

    /// <summary>
    /// Generates an AES key.
    /// </summary>
    /// <param name="size">Specifies the desired key size.</param>
    /// <returns>AES key.</returns>
    public static string GenerateEncryptionKey(KeySize size)
    {
        using (var aes = Aes.Create())
        {
            int keySize = (int)size;

            if (aes.ValidKeySize(keySize))
            {
                aes.KeySize = keySize;
                aes.GenerateKey();

                return Convert.ToBase64String(aes.Key);
            }
            else
            {
                return null;
            }
        }
    }
\$\endgroup\$
  • \$\begingroup\$ That Substring call means you're going from 2^128 possible keys to only 2^64. Why would you want to do that? \$\endgroup\$ – Pieter Witvoet May 24 at 13:05
  • \$\begingroup\$ The enum seems fairly useless to me. A key size in bits is a key size in bits no matter the algorithm. \$\endgroup\$ – Jesse C. Slicer May 24 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.