29 votes

La clé spécifiée ne correspond pas à une taille valide pour cet algorithme.

J'ai avec ce code :

RijndaelManaged rijndaelCipher = new RijndaelManaged();

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

J'ai des lancers :

Specified key is not a valid size for this algorithm.

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

Quel est le problème avec ces cordes ? Pouvez-vous me donner des exemples de chaînes de caractères ?

49voto

Rasmus Faber Points 24195

La chaîne "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678912", une fois décodée en base64, donne 48 octets (384 bits). RijndaelManaged supporte les clés de 128, 192 et 256 bits.

Une clé valide de 128 bits est new byte[]{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F } ou si vous devez l'obtenir à partir de la base64 : Convert.FromBase64String("AAECAwQFBgcICQoLDA0ODw==") .

La taille de bloc par défaut est de 128 bits, de sorte que la même matrice d'octets fonctionnera comme l'IV.

2voto

Utilisez la classe de générateur de nombres aléatoires (RNGCryptoServiceProvider) pour remplir un tampon spécifié avec des octets aléatoires comme suit :

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;

Notez que le même processus pourrait être utilisé pour dériver une clé. J'espère que cela vous aidera.

1voto

logicnp Points 4509

L'algorithme RijndaelManaged supporte des longueurs de clé de 128, 192 ou 256 bits. Votre clé est-elle de l'une de ces tailles ?

0voto

Alen.Toma Points 490

Voici la classe que j'ai créée

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;
                        }
                    }
                }
            }
        }
    }
}

-6voto

avatas Points 16

Je ne connais pas la longueur de rijndaelCipher.Key. si elle est de 24, alors rijndaelCipher.Key = s.SubString(0, 24) ;

C'est si facile.

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X