Domanda

Sto usando i metodi AES qui: http : //msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx

Voglio avere un valore di stringa che convertirò in array di byte e lo passerò al metodo di crittografia AES. Quanti caratteri deve essere la stringa per produrre la dimensione di array di byte corretta prevista dal metodo?

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

    }
È stato utile?

Soluzione

La dimensione del testo normale non ha importanza. Assicurati di utilizzare esattamente lo stesso IV e chiave insieme ai byte crittografati nel metodo decryptStringFromBytes_AES (byte [] cipherText, byte [] Key, byte [] IV). Ciò ti restituirà il testo in chiaro inserito.

Ad esempio:


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

Qui dovresti vedere che il testo normale e il testo normale sono ancora gli stessi. Ora vai avanti e cambia plain_text in tutto quello che vuoi e vedi che funziona bene.

I valori predefiniti per RijndaelManaged sono:
BlockSize: 128
KeySize: 256
Modalità: CipherMode.CBC
Imbottitura: PaddingMode.PKCS7

Le dimensioni IV valide sono:
128, 192, 256 bit (questa è la BlockSize, assicurati di impostarla sulla dimensione IV che stai utilizzando)
Le dimensioni chiave valide sono:
128, 192, 256 bit (questo è il KeySize, assicurati di impostarlo sulla chiave di dimensione che stai usando)

Ciò significa che il byte [] iv può essere 16, 24 o 32 byte (nell'esempio precedente i suoi 16 byte) e il tasto byte [] può anche essere 16, 24 o 32 byte (nell'esempio precedente i suoi 16 byte).

Spero che sia d'aiuto.

Altri suggerimenti

Per questo devi riempire. In realtà, la pagina che hai collegato ha un esempio di riempimento (in C ++).

Con i padding è possibile crittografare blocchi di dimensioni non standard.

Non convertire una stringa nella sua rappresentazione in byte Unicode. Sarà troppo difficile verificare la lunghezza corretta e non fornire una randomizzazione sufficiente.

Potresti fare quanto segue: utilizzare una funzione di derivazione chiave . Si desidera un array di byte a lunghezza fissa per l'input della funzione. Questo è ciò che Rfc2898 è il migliore in.

Quindi, crea un nuovo oggetto 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.
        // ...
    }
}

Per un esempio di come l'ho usato, guarda il mio progetto usando Rijndael . Ho un passaggio per la password in cui prendo una stringa e ottengo la matrice e la matrice di byte IV usando il metodo sopra.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top