Преобразование кода RijndaelManaged в код AesManaged

Я получил этот блок кода:

    public static string DoPrefixCipherEncrypt(string strIn, byte[] btKey)
    {
        if (strIn.Length < 1)
            return strIn;

        // Convert the input string to a byte array 
        byte[] btToEncrypt = System.Text.Encoding.Unicode.GetBytes(strIn);
        RijndaelManaged cryptoRijndael = new RijndaelManaged();
        cryptoRijndael.Mode =
        CipherMode.ECB;//Doesn't require Initialization Vector 
        cryptoRijndael.Padding =
        PaddingMode.PKCS7;


        // Create a key (No IV needed because we are using ECB mode) 
        ASCIIEncoding textConverter = new ASCIIEncoding();

        // Get an encryptor 
        ICryptoTransform ictEncryptor = cryptoRijndael.CreateEncryptor(btKey, null);


        // Encrypt the data... 
        MemoryStream msEncrypt = new MemoryStream();
        CryptoStream csEncrypt = new CryptoStream(msEncrypt, ictEncryptor, CryptoStreamMode.Write);


        // Write all data to the crypto stream to encrypt it 
        csEncrypt.Write(btToEncrypt, 0, btToEncrypt.Length);
        csEncrypt.Close();


        //flush, close, dispose 
        // Get the encrypted array of bytes 
        byte[] btEncrypted = msEncrypt.ToArray();


        // Convert the resulting encrypted byte array to string for return 
        return (Convert.ToBase64String(btEncrypted));
    }

    private static List<int> GetRandomSubstitutionArray(string number)
    {
        // Pad number as needed to achieve longer key length and seed more randomly.
        // NOTE I didn't want to make the code here available and it would take too longer to clean, so I'll tell you what I did. I basically took every number seed that was passed in and prefixed it and  postfixed it with some values to make it 16 characters long and to get a more unique result. For example:
        // if (number.Length = 15)
        //    number = "Y" + number;
        // if (number.Length = 14)
        //    number = "7" + number + "z";
        // etc - hey I already said this is a hack ;)

        // We pass in the current number as the password to an AES encryption of each of the
        // digits 0 - 9. This returns us a set of values that we can then sort and get a 
        // random order for the digits based on the current state of the number.
        Dictionary<string, int> prefixCipherResults = new Dictionary<string, int>();
        for (int ndx = 0; ndx < 10; ndx++)
            prefixCipherResults.Add(DoPrefixCipherEncrypt(ndx.ToString(), Encoding.UTF8.GetBytes(number)), ndx);

        // Order the results and loop through to build your int array.
        List<int> group = new List<int>();
        foreach (string key in prefixCipherResults.Keys.OrderBy(k => k))
            group.Add(prefixCipherResults[key]);

        return group;
    }

по этой ссылке Зашифруйте номер на другой номер того же длина

Мне нужно преобразовать / настроить DoPrefixCypherEncrypt на AesManaged вместо RijdaelManaged.

Спасибо, парни

ОБНОВЛЕНИЕ: Спасибо за все ваши ответы:

В конце концов я нашел другой способ сделать это, используя классы, доступные в WP 8.1.

Вместо:

        public static string DoPrefixCipherEncrypt(string strIn, byte[] btKey)
    {
        if (strIn.Length < 1)
            return strIn;

        // Convert the input string to a byte array 
        byte[] btToEncrypt = System.Text.Encoding.Unicode.GetBytes(strIn);

        AesManaged cryptoRijndael = new AesManaged();
        cryptoRijndael.Mode = CipherMode.ECB; cryptoRijndael.Padding = PaddingMode.PKCS7; //Mode Doesn't require Initialization Vector 

        // Create a key (No IV needed because we are using ECB mode) 
        ASCIIEncoding textConverter = new ASCIIEncoding();
        // Get an encryptor 
        ICryptoTransform ictEncryptor = cryptoRijndael.CreateEncryptor(btKey, null);
        // Encrypt the data... 
        MemoryStream msEncrypt = new MemoryStream();
        CryptoStream csEncrypt = new CryptoStream(msEncrypt, ictEncryptor, CryptoStreamMode.Write);

        // Write all data to the crypto stream to encrypt it 
        csEncrypt.Write(btToEncrypt, 0, btToEncrypt.Length); csEncrypt.Close(); //flush, close, dispose 
        // Get the encrypted array of bytes 
        byte[] btEncrypted = msEncrypt.ToArray();

        // Convert the resulting encrypted byte array to string for return 
        return (Convert.ToBase64String(btEncrypted));
    }

который совместим с не WinRT .NET.

Я смог использовать:

    public static string DoPrefixCipherEncrypt(string strIn, byte[] btKey)
    {
        if (strIn.Length < 1)
            return strIn;

        IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf16LE);
        IBuffer keyMaterial = CryptographicBuffer.CreateFromByteArray(btKey);

        SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
        // create symmetric key from derived password key
        CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

        var buffEncrypted = CryptographicEngine.Encrypt(symmKey, plainBuffer, null);
        var strEncrypted = CryptographicBuffer.EncodeToBase64String(buffEncrypted);

        return strEncrypted;
    }

person bolaji    schedule 29.08.2014    source источник
comment
А какой у вас вопрос?   -  person Oğuz Sezer    schedule 29.08.2014
comment
Я не понимаю вопроса - знаете ли вы, что алгоритм Rijndael и AES на самом деле одно и то же?   -  person Marwie    schedule 29.08.2014
comment
Я хочу использовать это шифрование в Windows / Phone 8.1 не использует System.Security.Cryptography, поэтому мой вопрос: мне нужен код, который я могу использовать с классами Windows.Security.Cryptography или любым другим применимым. Спасибо   -  person bolaji    schedule 29.08.2014
comment
Почему бы тебе просто не сделать это?   -  person President James K. Polk    schedule 29.08.2014


Ответы (1)


Просто замените создание и объявление RijndaelManaged на AesManaged:

AesManaged cryptoRijndael = new AesManaged();

Я попробовал, и он отлично работает. Я бы рекомендовал также переименовать имя переменной cryptoRijndael - но это ничего не изменит в работе кода.

В MSDN есть пример использования AesManaged со следующим утверждением:

Алгоритм AES - это, по сути, симметричный алгоритм Rijndael с фиксированным размером блока и количеством итераций. Этот класс работает так же, как класс RijndaelManaged, но ограничивает блоки до 128 бит и не допускает режимы обратной связи.

Так что просто замените ссылки RijndaelManaged на AesManaged. Если вы не используете его за пределами описанных ограничений, с вами все будет в порядке.

Строго говоря, AES является подмножеством Rijndael, поэтому Rijndael Managed уже должен охватывать все, что вы необходимость.

Из Википедии:

AES основан на шифре Rijndael [5], разработанном двумя бельгийскими криптографами, Joan Daemen и Vincent Rijmen, которые подали предложение в NIST во время процесса выбора AES.

person Marwie    schedule 29.08.2014
comment
Спасибо. В Windows / Phone 8.1 нет Rijndael, но я узнал, что у него есть AesManaged. - person bolaji; 29.08.2014
comment
К сожалению, в WinRT нет класса AesManaged. В конце концов я нашел другой способ сделать это - person bolaji; 02.09.2014
comment
ПРИМЕЧАНИЕ. Этот ответ также относится к Windows .NET Framework, а не только к Windows Mobile 8.x. - person Matt; 22.06.2017