Pergunta

Eu estou usando os métodos AES aqui: http : //msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx

Eu quero ter um valor de cadeia que eu irá converter para matriz de bytes e passá-lo para o método de criptografar AES. Quantos caracteres devem a string ser produzir o tamanho correto matriz de bytes que o espera método?

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();

    }
Foi útil?

Solução

O tamanho do texto simples não importa. Apenas certifique-se que você usa exatamente o mesmo IV e Key juntamente com os bytes codificados no decryptStringFromBytes_AES (byte [] texto cifrado, byte [] Key, byte [] IV) método. Isso vai voltar para você o texto simples entrou.

Por exemplo:


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

Aqui você verá que texto simples e de texto simples de novo são as mesmas. Agora vá em frente e mudança plain_text a qualquer coisa que você quer e ver que esta multa funciona.

Os valores padrão para RijndaelManaged são:
BlockSize: 128
KeySize: 256
Mode: CipherMode.CBC
Padding: PaddingMode.PKCS7

Os tamanhos IV válidos são:
128, 192, 256 bits (Este é o BlockSize, certifique-se de configurá-lo para o tamanho IV você está usando)
Os tamanhos de chaves válidas são:
128, 192, 256 bits (Este é o KeySize, certifique-se de configurá-lo para a chave tamanho que você está usando)

Isto significa que o iv byte [] pode ser 16, 24, ou 32 bytes (no meu exemplo acima seus 16 bytes) e o byte [] chave pode também ser 16, 24, ou 32 bytes (no meu exemplo acima seus 16 bytes).

Espero que ajude.

Outras dicas

Você precisa estofo para isso. Na verdade, a página que você ligado tem um exemplo de preenchimento (em C ++).

Com guarnição, você pode criptografar tamanhos não bloco padrão.

Do not converter uma string em sua representação byte Unicode. Será muito difícil para verificar o comprimento certo, e não fornecer randomização suficiente.

Você pode fazer o seguinte: Use um chave derivação função . Você quer um array de bytes de comprimento fixo para a entrada da função. Isto é o que RFC2898 é melhor em.

Assim, criar um novo 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 um exemplo de como eu usei isso, confira meu projeto usando Rijndael . Tenho um passo senha onde eu tomar uma corda e pegar a chave e IV matrizes de bytes usando o método acima.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top