2010-05-27 2 views
3

Я потратить некоторое время на изучение, как использовать RijndaelManaged библиотеки в .NET, и разработал следующую функцию, чтобы проверить шифрование текста с небольшими изменениями из библиотеки MSDN:Rijndael удалось: открытый текст длиной detction

Function encryptBytesToBytes_AES(ByVal plainText As Byte(), ByVal Key() As Byte, ByVal IV() As Byte) As Byte() 
     ' Check arguments. 
     If plainText Is Nothing OrElse plainText.Length <= 0 Then 
      Throw New ArgumentNullException("plainText") 
     End If 
     If Key Is Nothing OrElse Key.Length <= 0 Then 
      Throw New ArgumentNullException("Key") 
     End If 
     If IV Is Nothing OrElse IV.Length <= 0 Then 
      Throw New ArgumentNullException("IV") 
     End If 

     ' Declare the RijndaelManaged object 
     ' used to encrypt the data. 
     Dim aesAlg As RijndaelManaged = Nothing 

     ' Declare the stream used to encrypt to an in memory 
     ' array of bytes. 
     Dim msEncrypt As MemoryStream = Nothing 

     Try 
      ' Create a RijndaelManaged object 
      ' with the specified key and IV. 
      aesAlg = New RijndaelManaged() 
      aesAlg.BlockSize = 128 
      aesAlg.KeySize = 128 
      aesAlg.Mode = CipherMode.ECB 
      aesAlg.Padding = PaddingMode.None 
      aesAlg.Key = Key 
      aesAlg.IV = IV 

       ' Create a decrytor to perform the stream transform. 
       Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV) 

       ' Create the streams used for encryption. 
       msEncrypt = New MemoryStream() 
       Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write) 
        Using swEncrypt As New StreamWriter(csEncrypt) 

         'Write all data to the stream. 
         swEncrypt.Write(plainText) 
        End Using 
       End Using 

     Finally 
      ' Clear the RijndaelManaged object. 
      If Not (aesAlg Is Nothing) Then 
       aesAlg.Clear() 
      End If 
     End Try 
     ' Return the encrypted bytes from the memory stream. 
     Return msEncrypt.ToArray() 

    End Function 

Вот фактический код, который я звоню encryptBytesToBytes_AES() с:

Private Sub btnEncrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEncrypt.Click 
    Dim bZeroKey As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0} 
    PrintBytesToRTF(encryptBytesToBytes_AES(bZeroKey, bZeroKey, bZeroKey)) 
End Sub 

Однако, я получаю исключение брошено на swEncrypt.Write(plainText) о том, что «Длина данных для шифрования является недействительной.

Однако я знаю, что размер моего ключа iv и открытого текста составляет 16 байт == 128 бит == aesAlg.BlockSize. Почему это бросает это исключение? Это потому, что StreamWriter пытается создать String (якобы с некоторой кодировкой), и ему не нравится & H0 как значение?


EDIT: Я думаю, что нужно придумать новый способ зашифровать массив байтов, кроме использования StreamWriter. Gander на MSDN page показывает, что сначала это сделает какое-то преобразование строк, чего я не хочу. Есть идеи?

+2

Возможно, это возражение, потому что вы просите для режима ECB, но включая IV (который не используется в ЕЦБ)? –

+0

@Jerry - Попробуй, как ты правильно относишься к IV. –

+0

@ Джерри - нет, все равно случается, даже когда я меняю код, чтобы не установить IV. Но хорошее наблюдение. –

ответ

1

В этом случае нельзя использовать StreamWriter и не нужно.
StreamWriter не принимает Byte() в качестве аргумента.

Вы можете изменить вашу функцию шифрования следующим образом:

Function encryptBytesToBytes_AES(ByVal plainText As Byte(), ByVal Key() As Byte, ByVal IV() As Byte) As Byte() 
    ' Check arguments.' 
    If plainText Is Nothing OrElse plainText.Length <= 0 Then 
     Throw New ArgumentNullException("plainText") 
    End If 
    If Key Is Nothing OrElse Key.Length <= 0 Then 
     Throw New ArgumentNullException("Key") 
    End If 
    If IV Is Nothing OrElse IV.Length <= 0 Then 
     Throw New ArgumentNullException("IV") 
    End If 

    ' Declare the RijndaelManaged object' 
    ' used to encrypt the data.' 
    Dim aesAlg As RijndaelManaged = Nothing 

    Dim encryptedData As Byte() 

    Try 
     ' Create a RijndaelManaged object' 
     ' with the specified key and IV.' 
     aesAlg = New RijndaelManaged() 
     aesAlg.BlockSize = 128 
     aesAlg.KeySize = 128 
     aesAlg.Mode = CipherMode.ECB 
     aesAlg.Padding = PaddingMode.None 
     aesAlg.Key = Key 
     aesAlg.IV = IV 

     ' Create a decrytor to perform the stream transform.' 
     Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor() 

     ' Create the streams used for encryption.' 
     Using msEncrypt As New MemoryStream() 

      Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write) 
       csEncrypt.Write(plainText, 0, plainText.Length) 
       csEncrypt.FlushFinalBlock() 
      End Using 
      encryptedData = msEncrypt.ToArray() 
     End Using 

    Finally 
     ' Clear the RijndaelManaged object.' 
     If Not (aesAlg Is Nothing) Then 
      aesAlg.Clear() 
     End If 
    End Try 
    ' Return the encrypted bytes from the memory stream.' 
    Return encryptedData 
End Function 
+0

Это решило мою проблему. Большое спасибо. –

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