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

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);
        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;
    }
  • 0
    А какой у тебя вопрос?
  • 0
    Я не понимаю вопроса - знаете ли вы, что алгоритм Rijndael и AES на самом деле одно и то же?
Показать ещё 2 комментария
Теги:
aes
cryptography
rijndaelmanaged

1 ответ

1

Просто замените экземпляр и объявление RijndaelManaged с помощью AesManaged:

AesManaged cryptoRijndael = new AesManaged();

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

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

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

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

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

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

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

  • 0
    Благодарю. Windows / Phone 8.1 не имеет Rijndael, но я узнал, что есть AesManaged
  • 0
    Извините, в WinRT нет класса AesManaged. В конце концов я нашел другой способ сделать это
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню