2014-08-29 3 views
1

Я получил этот блок кода:Преобразовать 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; 
    } 

по этой ссылке Encrypt a number to another number of the same length

мне нужна "DoPrefixCypherEncrypt" конвертируется/доведенным до AesManaged вместо RijdaelManaged.

Спасибо, ребята

UPDATE: Спасибо за все ваши ответы:

В конце концов я нашел еще один способ сделать это, используя доступные классы в 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 на самом деле одно и то же? – Marwie

+0

Я хочу использовать это шифрование в Windows/Phone 8.1, не использует System.Security.Cryptography, поэтому мой вопрос: мне нужен код, который я могу использовать с классами Windows.Security.Cryptography или любым другим применимым. Спасибо – bolaji

ответ

1

Просто замените экземпляр и декларацию RijndaelManaged с AesManaged:

AesManaged cryptoRijndael = new AesManaged(); 

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

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

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

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

Строго говоря, AES is a subset of Rijndael, так что управляемый Rijndael должен уже покрывать все, что вам нужно.

От Wikipedia:

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

+0

Спасибо.Windows/Phone 8.1 не имеет Rijndael, но я узнал, что у него есть AesManaged – bolaji

+0

К сожалению, в WinRT нет класса AesManaged. В конце концов я нашел другой способ сделать это. – bolaji

+0

ПРИМЕЧАНИЕ. Этот ответ также относится к Windows .NET Framework, а не только к Windows Mobile 8.x – Matt

Смежные вопросы