Pregunta

Estoy usando los métodos AES aquí: http : //msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx

Quiero tener un valor de cadena que convertiré en matriz de bytes y pasarlo al método de cifrado AES. ¿Cuántos caracteres debe tener la cadena para producir el tamaño de matriz de bytes correcto que el método espera?

static byte[] encryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");

        // Declare the stream used to encrypt to an in memory
        // array of bytes.
        MemoryStream msEncrypt = null;

        // Declare the RijndaelManaged object
        // used to encrypt the data.
        RijndaelManaged aesAlg = null;

        try
        {
            // Create a RijndaelManaged object
            // with the specified key and IV.
            aesAlg = new RijndaelManaged();
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            msEncrypt = new MemoryStream();
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {

                    //Write all data to the stream.
                    swEncrypt.Write(plainText);
                }
            }

        }
        finally
        {

            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        // Return the encrypted bytes from the memory stream.
        return msEncrypt.ToArray();

    }
¿Fue útil?

Solución

El tamaño del texto plano no importa. Solo asegúrese de usar exactamente el mismo IV y clave junto con los bytes encriptados en el método decryptStringFromBytes_AES (byte [] cipherText, byte [] Key, byte [] IV). Eso le devolverá el texto sin formato introducido.

Por ejemplo:


string plain_text = "Cool this works";
byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                                           0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
byte[] key = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
                                           0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
byte[] encrytped_text = encryptStringToBytes_AES(plain_text, key, iv);
string plain_text_again = decryptStringFromBytes_AES(encrypted_text, key, iv);

Aquí debería ver que el texto plano y el texto plano nuevamente son lo mismo. Ahora continúe y cambie plain_text a lo que quiera y vea que esto funciona bien.

Los valores predeterminados para RijndaelManaged son:
Tamaño de bloque: 128
KeySize: 256
Modo: CipherMode.CBC
Relleno: PaddingMode.PKCS7

Los tamaños IV válidos son:
128, 192, 256 bits (este es el tamaño de bloque, asegúrese de configurarlo en el tamaño IV que está utilizando)
Los tamaños de clave válidos son:
128, 192, 256 bits (Este es el KeySize, asegúrese de configurarlo en la clave de tamaño que está usando)

Esto significa que el byte [] iv puede tener 16, 24 o 32 bytes (en mi ejemplo anterior, sus 16 bytes) y la clave del byte [] también puede tener 16, 24 o 32 bytes (en mi ejemplo anterior sus 16 bytes).

Espero que eso ayude.

Otros consejos

Necesitas relleno para eso. En realidad, la página que ha vinculado tiene un ejemplo de relleno (en C ++).

Con rellenos, puede cifrar tamaños de bloque no estándar.

No convierta una cadena en su representación de byte Unicode. Será demasiado difícil verificar la longitud correcta y no proporcionará suficiente aleatorización.

Puede hacer lo siguiente: use una función de derivación de clave . Desea una matriz de bytes de longitud fija para la entrada de la función. Esto es lo que Rfc2898 es mejor en.

Entonces, cree un nuevo objeto Rfc2898:

using PBKDF2 = System.Security.Cryptography.Rfc2898DeriveBytes;

class Example {
    byte[] mySalt = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

    void Initialize( string password ) {
        PBKDF2 kdf = new PBKDF2( password, mySalt );
        // Then you have your algorithm
        // When you need a key: use:
        byte[] key = kdf.GetBytes( 16 ); // for a 128-bit key (16*8=128)

        // You can specify how many bytes you need. Same for IV.
        byte[] iv = kdf.GetBytes( 16 ); // 128 bits again.

        // And then call your constructor, etc.
        // ...
    }
}

Para ver un ejemplo de cómo he usado esto, consulte mi proyecto usando Rijndael . Tengo un paso de contraseña donde tomo una cadena y obtengo la clave y los conjuntos de bytes iv usando el método anterior.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top