Specified key is not a valid size for this algorithm
Asked Answered
G

5

70

I have with this code:

RijndaelManaged rijndaelCipher = new RijndaelManaged();
              
// Set key and IV
rijndaelCipher.Key = Convert.FromBase64String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678912");
rijndaelCipher.IV = Convert.FromBase64String("1234567890123456789012345678901234567890123456789012345678901234");

I get this exception thrown:

Specified key is not a valid size for this algorithm.

Specified initialization vector (IV) does not match the block size for this algorithm.

What's wrong with this strings ? Can I count at some examples strings from you?

Gagne answered 27/5, 2010 at 7:27 Comment(0)
S
110

The string "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678912" when base64-decoded yields 48 bytes (384 bits). RijndaelManaged supports 128, 192 and 256 bit keys.

A valid 128-bit key is new byte[]{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F } or if you need to get it from base64 : Convert.FromBase64String("AAECAwQFBgcICQoLDA0ODw==").

The default blocksize is 128 bits, so the same byte-array will work as the IV.

Stonemason answered 27/5, 2010 at 8:32 Comment(2)
Interesting coincidence... that's the same secret key I use for all my encryption algorithms...Hexapody
Actually, it seems to support a few more keysizes but that's because of a bug. Just don't forget to work around that bug during unit testing.Duramen
P
6

Use the random number generator class (RNGCryptoServiceProvider) to fill a specified buffer with random bytes as follows:

var numberOfBits = 256; // or 192 or 128, however using a larger bit size renders the encrypted data harder to decipher

var ivBytes = new byte[numberOfBits / 8]; // 8 bits per byte

new RNGCryptoServiceProvider().GetBytes(ivBytes);

var rijndaelManagedCipher = new RijndaelManaged();

//Don't forget to set the explicitly set the block size for the IV if you're not using the default of 128

rijndaelManagedCipher.BlockSize = 256;

rijndaelManagedCipher.IV = ivBytes;

Note the same process could be used to derive a key. Hope this helps.

Papuan answered 27/10, 2013 at 16:5 Comment(2)
If you use random numbers to generate a key to encrypt a password, how can you come back in later (generating a different random key) and confirm that the password is correct?Rosenberg
@jp2code This is actually a fantastic and secure solution so long as you store the ivBytes somewhere, which is what I assume this answer intends for you to do (but doesn't explicitly show)Longhair
S
2

The RijndaelManaged algorithm supports key lengths of 128, 192, or 256 bits. Is your key one of these sizes?

Shimkus answered 27/5, 2010 at 7:32 Comment(2)
I don't understand :/ my string to encode has lenght 40 - 200Gagne
My byte array after I convert it from string is exactly 16 bytes but it is still not accepting itMandorla
C
0

here is the class i created

public class ByteCipher
{
    // This constant is used to determine the keysize of the encryption algorithm in bits.
    // We divide this by 8 within the code below to get the equivalent number of bytes.
    private int _Keysize = (int)GlobalConfiguration.DataEncode_Key_Size;

    private byte[] saltStringBytes;

    private byte[] ivStringBytes;
    // This constant determines the number of iterations for the password bytes generation function.
    private const int DerivationIterations = 1000;
    private string _passPhrase = GlobalConfiguration.DataEncode_Key;

    private const string salt128 = "kljsdkkdlo4454GG";
    private const string salt256 = "kljsdkkdlo4454GG00155sajuklmbkdl";

    public ByteCipher(string passPhrase = null, DataCipherKeySize keySize = DataCipherKeySize.Key_128)
    {
        if (!string.IsNullOrEmpty(passPhrase?.Trim()))
            _passPhrase = passPhrase;
        _Keysize = keySize == DataCipherKeySize.Key_256 ? 256 : 128;
        saltStringBytes = _Keysize == 256 ? Encoding.UTF8.GetBytes(salt256) : Encoding.UTF8.GetBytes(salt128);
        ivStringBytes = _Keysize == 256 ? Encoding.UTF8.GetBytes("SSljsdkkdlo4454Maakikjhsd55GaRTP") : Encoding.UTF8.GetBytes("SSljsdkkdlo4454M");
    }

    public byte[] Encrypt(byte[] plainTextBytes)
    {
        if (plainTextBytes.Length <= 0)
            return plainTextBytes;

        using (var password = new Rfc2898DeriveBytes(_passPhrase, saltStringBytes, DerivationIterations))
        {
            var keyBytes = password.GetBytes(_Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = _Keysize;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                            var cipherTextBytes = saltStringBytes;
                            cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                            cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                            memoryStream.Close();
                            cryptoStream.Close();
                            return cipherTextBytes;
                        }
                    }
                }
            }
        }
    }

    public byte[] Decrypt(byte[] cipherTextBytesWithSaltAndIv)
    {
        if (cipherTextBytesWithSaltAndIv.Length <= 0)
            return cipherTextBytesWithSaltAndIv;
        var v = Encoding.UTF8.GetString(cipherTextBytesWithSaltAndIv.Take(_Keysize / 8).ToArray());
        if (v != salt256 && v != salt128)
            return cipherTextBytesWithSaltAndIv;

        var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((_Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((_Keysize / 8) * 2)).ToArray();

        using (var password = new Rfc2898DeriveBytes(_passPhrase, saltStringBytes, DerivationIterations))
        {
            var keyBytes = password.GetBytes(_Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                symmetricKey.BlockSize = _Keysize;

                using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var plainTextBytes = new byte[cipherTextBytes.Length];
                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            memoryStream.Close();
                            cryptoStream.Close();
                            return plainTextBytes;
                        }
                    }
                }
            }
        }
    }
}
Cephalothorax answered 15/3, 2018 at 19:7 Comment(0)
R
-6

I don't know the length of rijndaelCipher.Key.

If it is 24, then rijndaelCipher.Key = s.SubString(0, 24);

Rarotonga answered 21/11, 2014 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.