I am converting some VB6 code to VB.Net. The code encrypts 16 bytes of data, triple DES, 128 bit key, ECB mode. Using the same data and the same key, the VB6 code gives me 2 blocks and the VB.Net code gives me 3 blocks. The first two blocks match the two blocks from the VB6 code. If I remove one byte from the VB.Net data, I get two blocks. My understanding is that I should not get three blocks until I encrypt 17 bytes of data. Does anyone know why I am getting three blocks of encrypted data from VB.Net?
Here is the VB.Net code.Dim TDes As New TripleDESCryptoServiceProvider
Dim KeyString As String = "0102030405060708090A0B0C0D0E0F10"
Dim DataString As String = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
Dim DataBytes(15) As Byte
Dim KeyBytes(15) As Byte
Dim EncryptBytes() As Byte
Dim EncryptString As String = ""
Dim x As Byte
For x = 0 To KeyString.Length - 1 Step 2
KeyBytes(x / 2) = Val("&h" & Mid(KeyString, x + 1, 2))
Next x
For x = 0 To DataString.Length - 1 Step 2
DataBytes(x / 2) = Val("&h" & Mid(DataString, x + 1, 2))
Next x
TDes.KeySize = 128
TDes.Key = KeyBytes
TDes.Mode = CipherMode.ECB
Dim ms As New System.IO.MemoryStream
Dim encStream As New CryptoStream(ms, TDes.CreateEncryptor(), _
System.Security.Cryptography.CryptoStreamMode.Write)
encStream.Write(DataBytes, 0, DataBytes.Length)
encStream.FlushFinalBlock()
EncryptBytes = ms.ToArray()
For x = 0 To EncryptBytes.Length - 1
EncryptString = EncryptString & Mid("0" & Hex(EncryptBytes(x)), _
Len(Hex(EncryptBytes(x))), 2)
Next x
MessageBox.Show(EncryptString & " - " & Len(EncryptString) / 2)
Thanks,
Mike
解决方案
I suspect this is down to padding and the default padding mode which AFAIK is PKCS7. See RFC5652 para 6.3
(http://tools.ietf.org/html/rfc5652#section-6.3[^]) which shows that PKCS7 padding always adds at least 1 byte. So 16 bytes of plain text should encrypt to 3 blocks of cipher text (using PKCS7 padding).