Расшифровка 3Des с использованием другого ключа (из состояния шифрования), может успешно расшифровать

Я пробовал TripleDESCryptoServiceProvider (). И я немного изменил ключ шифрования / дешифрования, интересно, почему другой ключ может успешно расшифровать зашифрованный текст.

(Также я пробовал с указанием другого IV или без него, результат тот же)

Разница в ключах на TestKey1(5) = 4, TestKey2(5) = 5

Imports System.Net
Imports System.IO
Imports System.Security.Cryptography

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim tDESalg As New TripleDESCryptoServiceProvider()

        Dim Testkey1 As Byte() = UTF8Encoding.UTF8.GetBytes("Z4xC#49S3$3!A470&i0O51@5")

        ' Create a string to encrypt.
        Dim sData As String = "Here is some data to encrypt."

        ' Encrypt the string to an in-memory buffer.
        Dim Data As Byte() = TrippleDESCSPSample.EncryptTextToMemory(sData, Testkey1, tDESalg.IV)

        Dim Testkey2 As Byte() = UTF8Encoding.UTF8.GetBytes("Z4xC#59S3$3!A470&i0O51@5")
        Debug.Print(Testkey1.Equals(Testkey2))

        ' Decrypt the buffer back to a string.
        Dim Final As String = TrippleDESCSPSample.DecryptTextFromMemory(Data, Testkey2, tDESalg.IV)

        ' Display the decrypted string to the console.
        Response.Write(Final)
    End Sub



End Class


Class TrippleDESCSPSample


    Public Shared Function EncryptTextToMemory(Data As String, Key As Byte(), IV As Byte()) As Byte()
        Try
            ' Create a MemoryStream.
            Dim mStream As New MemoryStream()

            ' Create a CryptoStream using the MemoryStream 
            ' and the passed key and initialization vector (IV).
            Dim cStream As New CryptoStream(mStream, New TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV), CryptoStreamMode.Write)

            ' Convert the passed string to a byte array.
            Dim toEncrypt As Byte() = New ASCIIEncoding().GetBytes(Data)

            ' Write the byte array to the crypto stream and flush it.
            cStream.Write(toEncrypt, 0, toEncrypt.Length)
            cStream.FlushFinalBlock()

            ' Get an array of bytes from the 
            ' MemoryStream that holds the 
            ' encrypted data.
            Dim ret As Byte() = mStream.ToArray()

            ' Close the streams.
            cStream.Close()
            mStream.Close()

            ' Return the encrypted buffer.
            Return ret
        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Return Nothing
        End Try

    End Function

    Public Shared Function DecryptTextFromMemory(Data As Byte(), Key As Byte(), IV As Byte()) As String
        Try
            ' Create a new MemoryStream using the passed 
            ' array of encrypted data.
            Dim msDecrypt As New MemoryStream(Data)

            ' Create a CryptoStream using the MemoryStream 
            ' and the passed key and initialization vector (IV).
            Dim csDecrypt As New CryptoStream(msDecrypt, New TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), CryptoStreamMode.Read)

            ' Create buffer to hold the decrypted data.
            Dim fromEncrypt As Byte() = New Byte(Data.Length - 1) {}

            ' Read the decrypted data out of the crypto stream
            ' and place it into the temporary buffer.
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)

            'Convert the buffer into a string and return it.
            Return New ASCIIEncoding().GetString(fromEncrypt)
        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Return Nothing
        End Try
    End Function

End Class

person Eric F.    schedule 30.03.2015    source источник
comment
Интересный. Насколько я понимаю, внесение других изменений в ключ приводит к его сбою ...   -  person Jon Skeet    schedule 30.03.2015
comment
Насколько мне известно, неправильный ключ иногда может вызывать исключение, а иногда и нормально - без исключения.   -  person Eric F.    schedule 31.03.2015
comment
Для тех, кто наткнулся на эту ветку, краткий ответ на мой вопрос (прочитав ссылку, предоставленную выше @xanatos): 1. Даже размер ключа 3DES составляет 24 байта (= 24 символа), но он занимает всего 7 бит из каждого байта в качестве ключа. , оставшийся бит (каждого байта) - это бит четности, который многие библиотеки 3DES решили опустить. 2. Таким образом, изменение пятого байта с 4 на 5 не приводит к каким-либо изменениям в этих 7 битах библиотеки .Net, поэтому оба они считаются одним и тем же ключом. 3. Что, в свою очередь, делает дешифрование юридически возможным. Спасибо @xanatos   -  person Eric F.    schedule 31.03.2015