0

I have the code below that works with 128 bit Hex Key. However, when i supply 256 bit Hex key (or higher) it throws error

Message: System.ArgumentException : Specified key is not a valid size for this algorithm. Parameter name: rgbKey

        public static string Encrypt(string text, string keyString)
        {
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aesAlg = Aes.Create())
            {
                using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
                {
                    using (var msEncrypt = new MemoryStream())
                    {
                        using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(text);
                        }

                        var iv = aesAlg.IV;

                        var decryptedContent = msEncrypt.ToArray();

                        var result = new byte[iv.Length + decryptedContent.Length];

                        Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
                        Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);

                        return Convert.ToBase64String(result);
                    }
                }
            }
        }

How do i use AES with 256 bit or higher Key?

LP13
  • 30,567
  • 53
  • 217
  • 400
  • 1
    AES only accepts keys of 128, 192, or 256 bits. If you have a hex-encoded key than you must first apply a hex-decoder to it. Using UTF8.GetBytes() is *not* hex-decoding. – President James K. Polk Sep 26 '18 at 21:58
  • i used http://www.allkeysgenerator.com/Random/Security-Encryption-Key-Generator.aspx to generate 128 bit Hex Key.. I try 256 bit.. i get exception – LP13 Sep 26 '18 at 22:10

1 Answers1

-1

Try setting the Padding mode to PKCS7.

aesAlg.Padding = PaddingMode.PKCS7.

  • Ah, my bad. You said its a Hex Key. You need decode it and then pass it to the create encryptor method. https://stackoverflow.com/a/724905/3741984 – Vadim Condratiev Sep 27 '18 at 13:59