Как кодировать метод расшифровки для метода шифрования здесь, в C # - PullRequest
0 голосов
/ 09 февраля 2012

Мне удалось собрать пример шифрования, как показано ниже, но во время расшифровки я получаю неверные данные (исключение).Как я должен расшифровать

Метод шифрования

public static string EncryptWithAes(string plainText, byte[] key, byte[] initiationVector)
        {

            byte[] cryptoBytes = Encoding.UTF8.GetBytes(plainText);

            using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
            {
                aesAlgorithm.Key = key;
                aesAlgorithm.IV = initiationVector;
                aesAlgorithm.Mode = CipherMode.ECB;
                using (ICryptoTransform encryptoTransform = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    cryptoBytes = encryptoTransform.TransformFinalBlock(cryptoBytes, 0, cryptoBytes.Length);
                }
            }
            return Convert.ToBase64String(cryptoBytes);
        }

Метод расшифровки

 public static string DecryptAesCryptoString(string cipherText, byte[] key, byte[] initiationVector)
        {
            byte[] decryptedByte;
            using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
            {
                aesAlgorithm.Key = key;
                aesAlgorithm.IV = initiationVector;
                aesAlgorithm.Mode = CipherMode.ECB;

                using (ICryptoTransform decryptoTransform = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    byte[] cipherBytes = Convert.FromBase64String(cipherText);
                    decryptedByte = decryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);

                }
            }
            return Encoding.UTF8.GetString(decryptedByte);
        }

Я думаю, что проблема со всеми кодировками, которые идут внутри этих методов

Пример данных

plainText = stackoverflow

base64encoded Key = B8Y/6doxwqU870C6jzYWhsr3hKSLokAOkkLCDiy+TS4= (его легко преобразовать в байты, не так ли)

base64encoded IV = NZIpD60eBmdsOFFhA2bfvw==

encryptedValue = 77+977+977+977+977+9Ce+/ve+/vQ3vv70F77+9UzHvv73vv70=

Я предоставляю то же зашифрованное значение, IV и ключ для расшифровки в Stackoverflow

Ответы [ 3 ]

1 голос
/ 09 февраля 2012

Я думаю, что ваша проблема в длине вашего IV и, возможно, ключ.Насколько я помню, IV должен быть длиной 16 байт, ключ имеет разные опции, вы должны посмотреть это.

// TEST:

        RijndaelManaged alg = new RijndaelManaged();

        alg.GenerateKey();
        alg.GenerateIV();

        byte[] key = alg.Key;
        byte[] iv = alg.IV;

        string text = "teststring";

        string encrypted = EncryptWithAes(text, key, iv);

        MessageBox.Show(encrypted);

        String result = DecryptAesCryptoString(encrypted, key, iv);

        MessageBox.Show(result);
1 голос
/ 09 февраля 2012

и, к сожалению, это, безусловно, было связано с проблемой кодирования.Теперь решено, как показано ниже:

Шифрование

public static string EncryptWithAes(string plainText, byte[] key, byte[] initiationVector)
        {
            byte[] cryptoBytes = Convert.FromBase64String(plainText);
            using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
            {
                aesAlgorithm.Key = key;
                aesAlgorithm.IV = initiationVector;
                aesAlgorithm.Mode = CipherMode.ECB;
                using (ICryptoTransform encryptoTransform = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    cryptoBytes = encryptoTransform.TransformFinalBlock(cryptoBytes, 0, cryptoBytes.Length);
                }
            }
            return Convert.ToBase64String(cryptoBytes);
        }

Расшифровка

public static string DecryptAesCryptoString(string cipherText, byte[] key, byte[] initiationVector)
{

    byte[] decryptedByte;
    using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
    {
        aesAlgorithm.Key = key;
        aesAlgorithm.IV = initiationVector;
        aesAlgorithm.Mode = CipherMode.ECB;
        using (ICryptoTransform decryptoTransform = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            decryptedByte = decryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);

        }
    }
    return Convert.ToBase64String(decryptedByte);
}
0 голосов
/ 09 февраля 2012

Почему бы вам не попробовать, удалив кодировку? Вот простая реализация :

public class RijndaelSimpleTest
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        string   plainText          = "Hello, World!";    // original plaintext

        string   passPhrase         = "Pas5pr@se";        // can be any string
        string   saltValue          = "s@1tValue";        // can be any string
        string   hashAlgorithm      = "SHA1";             // can be "MD5"
        int      passwordIterations = 2;                  // can be any number
        string   initVector         = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
        int      keySize            = 256;                // can be 192 or 128

        Console.WriteLine(String.Format("Plaintext : {0}", plainText));

        string  cipherText = RijndaelSimple.Encrypt(plainText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

        Console.WriteLine(String.Format("Encrypted : {0}", cipherText));

        plainText          = RijndaelSimple.Decrypt(cipherText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

        Console.WriteLine(String.Format("Decrypted : {0}", plainText));
    }
}
...