Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
3.75/5 (4 votes)
See more:
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
Posted
Updated 19-Apr-11 4:50am
v5
Comments
Prerak Patel 19-Apr-11 7:09am    
Provided code doesn't even run.
Henry Minute 19-Apr-11 11:46am    
Runs for me.
mikeef 19-Apr-11 10:50am    
I could not put the key I am using in the code, so I just filled it with FF. I have added a key that will not be considered "weak" and will run.

1 solution

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).
 
Share this answer
 
v2
Comments
Tarakeshwar Reddy 25-Apr-11 17:57pm    
Fixed your link

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900