Re: DES Encryption and Decryption using different keys gives 'Bad Data' exception

From: dean (abc_at_def.com)
Date: 06/04/03

  • Next message: Etienne Charland: "Re: user rights of the logged in user in .net"
    Date: Wed, 4 Jun 2003 12:27:11 +0200
    
    

    Thanks Ivan, I have attached the comments I recd from MS support on this.

    **********************
    301070.KB.EN-US HOW TO: Encrypt and Decrypt a File by Using Visual Basic
    .NET

    (http://support.microsoft.com/?id=301070)

     It contains the following about the Keys:

    The DESCryptoServiceProvider is based on Symmetric encryption algorithm. The
    symmetric encryption require a key and a initialization vector (IV) to
    encrypt data. To decrypt the data the user must possess the same key and IV
    and use the same encryption algorithm.

    ************************

    However I find this odd. If the DES algorithm merely transforms an input
    string to an output using a Key and IV etc, then how will it be able to
    determine what input key the cipher text was created with. I accept that to
    get the original plain text you need to use the same key (hence the name
    symmetric encryption) to decrypt. What do you think of the above statement?

    I have read that the process indicated is effectively triple des with a
    128bit key (112 without parity) but I can't confirm this because DES gives a
    bad data exception using different encrypt and decrypt keys (ie the 128
    split into 2) and using a 128 bit key that has the same first half and
    second half causes Triple DES to raise an exception becuase that is a weak
    key.

    I have attached the test harness code I am using to try this out. It
    contains a form and class. Hopefully this will highlight any errors.
    essentially I have to get the value stored in KCV1 by encrypting the string
    value of zero using the KEK component split into two and using DES.

    Thanks for the help

    Dean

    ********************************
    'The form code
    ********************************
    Imports System.Text

    Imports System.Security

    Imports System.Security.Cryptography

    Public Class Form1

    Inherits System.Windows.Forms.Form

    #Region " Windows Form Designer generated code "

    Public Sub New()

    MyBase.New()

    'This call is required by the Windows Form Designer.

    InitializeComponent()

    'Add any initialization after the InitializeComponent() call

    PerformStartup()

    End Sub

    'Form overrides dispose to clean up the component list.

    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

    If disposing Then

    If Not (components Is Nothing) Then

    components.Dispose()

    End If

    End If

    MyBase.Dispose(disposing)

    End Sub

    'Required by the Windows Form Designer

    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer

    'It can be modified using the Windows Form Designer.

    'Do not modify it using the code editor.

    Friend WithEvents Button1 As System.Windows.Forms.Button

    Friend WithEvents Button2 As System.Windows.Forms.Button

    Friend WithEvents lstOutput As System.Windows.Forms.ListBox

    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    Me.Button1 = New System.Windows.Forms.Button()

    Me.Button2 = New System.Windows.Forms.Button()

    Me.lstOutput = New System.Windows.Forms.ListBox()

    Me.SuspendLayout()

    '

    'Button1

    '

    Me.Button1.Location = New System.Drawing.Point(16, 16)

    Me.Button1.Name = "Button1"

    Me.Button1.Size = New System.Drawing.Size(152, 24)

    Me.Button1.TabIndex = 0

    Me.Button1.Text = "Calc KCV Using DES"

    '

    'Button2

    '

    Me.Button2.Location = New System.Drawing.Point(176, 16)

    Me.Button2.Name = "Button2"

    Me.Button2.Size = New System.Drawing.Size(152, 24)

    Me.Button2.TabIndex = 1

    Me.Button2.Text = "Calc Using Triple DES"

    '

    'lstOutput

    '

    Me.lstOutput.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or
    System.Windows.Forms.AnchorStyles.Bottom) _

    Or System.Windows.Forms.AnchorStyles.Left) _

    Or System.Windows.Forms.AnchorStyles.Right)

    Me.lstOutput.Location = New System.Drawing.Point(0, 48)

    Me.lstOutput.Name = "lstOutput"

    Me.lstOutput.Size = New System.Drawing.Size(336, 277)

    Me.lstOutput.TabIndex = 2

    '

    'Form1

    '

    Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)

    Me.ClientSize = New System.Drawing.Size(336, 325)

    Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.lstOutput,
    Me.Button2, Me.Button1})

    Me.Name = "Form1"

    Me.Text = "Form1"

    Me.ResumeLayout(False)

    End Sub

    #End Region

    'Friend Const KEK1 As String = "8F5E-6EBA-BC0E-2F92-49E5-C201-0708-C834"

    'Friend Const KCV1 As String = "94-F5-F0-D8-43-46-E7-7D"

    Friend Const KEK1 As String = "1111-1111-1111-1111-1111-1111-1111-1111"

    Friend Const KCV1 As String = "82-E1-36-65-B4-62-4D-F5"

    Private btTempStore(7) As Byte

    Private Sub PerformStartup()

    AddHandler Button1.Click, AddressOf CalcKCV1DESClick

    AddHandler Button2.Click, AddressOf CalcKCV1TDESClick

    End Sub

    'Generate a Key Check Value for Key Value 1 using DES so verify correct
    entry

    Private Sub CalcKCV1DESClick(ByVal sender As System.Object, ByVal e As
    System.EventArgs)

    Try

    Dim btKEK1() As Byte

    Dim btKL(7) As Byte

    Dim btKR(7) As Byte

    Dim sKEK1Converted As String

    Dim btBytesReturned2() As Byte

    Dim btBytesReturned3() As Byte

    Dim btBytesReturned4() As Byte

    Dim btInitVector(7) As Byte

    Dim sInitVector As String

    Dim oEncryptDecrypt As clsEncryptDecrypt

    oEncryptDecrypt = New clsEncryptDecrypt(CipherMode.CBC, PaddingMode.PKCS7)

    'Following on from the Guidance note methodology

    'STEP 1 - get the Byte array version of this string

    btKEK1 = ConvertKEKFromHexToByteArray(KEK1)

    'Break it into two 64 bit sub keys - Key left (KL) and Key Right (KR)

    Array.Copy(btKEK1, 0, btKL, 0, 8)

    Array.Copy(btKEK1, 8, btKR, 0, 8)

    'Get the Init Vector

    btInitVector = Encoding.UTF8.GetBytes("00000000")

    'STEP2 - encrypt 0 with a key = KL

    btBytesReturned2 = oEncryptDecrypt.DESEncrypt("0", btKL, btInitVector)

    btTempStore = btBytesReturned2

    lstOutput.Items.Add("KCV 1 calculation Step 1")

    lstOutput.Items.Add("DES Encrypted CipherText: " &
    BitConverter.ToString(btBytesReturned2))

    lstOutput.Items.Add("DES Encrypted Text: " &
    Encoding.UTF8.GetString(btBytesReturned2))

    'STEP3 - decrypt with a key = KR

    btBytesReturned3 = oEncryptDecrypt.DESDecrypt(btBytesReturned2, btKR,
    btInitVector)

    lstOutput.Items.Add("Step 3")

    lstOutput.Items.Add("DES Encrypted CipherText: " &
    BitConverter.ToString(btBytesReturned3))

    lstOutput.Items.Add("DES Encrypted Text: " &
    Encoding.UTF8.GetString(btBytesReturned3))

    'STEP2 - encrypt 0 with a key = KEK1

    btBytesReturned4 = oEncryptDecrypt.DESEncrypt(btBytesReturned3, btKL,
    btInitVector)

    lstOutput.Items.Add("Step 4")

    lstOutput.Items.Add("DES Encrypted CipherText: " &
    BitConverter.ToString(btBytesReturned4))

    lstOutput.Items.Add("DES Encrypted Text: " &
    Encoding.UTF8.GetString(btBytesReturned4))

    lstOutput.Items.Add("KCV Returned : " &
    BitConverter.ToString(btBytesReturned4))

    Catch exp As Exception

    HandleException(exp)

    End Try

    End Sub

    'Generate a Key Check Value for Key Value 1 using Triple DES so verify
    correct entry

    Private Sub CalcKCV1TDESClick(ByVal sender As System.Object, ByVal e As
    System.EventArgs)

    Try

    Dim btKEK1() As Byte

    Dim sKEK1Converted As String

    Dim btBytesReturned() As Byte

    Dim btInitVector() As Byte

    Dim sInitVector As String

    Dim oEncryptDecrypt As clsEncryptDecrypt

    oEncryptDecrypt = New clsEncryptDecrypt(CipherMode.CBC, PaddingMode.PKCS7)

    'Following on from the Guidance note methodology

    'STEP 1 - get the Byte array version of this string

    btKEK1 = ConvertKEKFromHexToByteArray(KEK1)

    'Get the Init Vector

    btInitVector = Encoding.UTF8.GetBytes("00000000")

    'STEP2 - encrypt 0 with a key = KEK1

    btBytesReturned = oEncryptDecrypt.TripleDESEncrypt("0", btKEK1,
    btInitVector)

    lstOutput.Items.Add("KCV 1 calculation")

    lstOutput.Items.Add("3DES Encrypted CipherText: " &
    BitConverter.ToString(btBytesReturned))

    lstOutput.Items.Add("3DES Encrypted Text: " &
    Encoding.UTF8.GetString(btBytesReturned))

    'Test that this can be decrypted

    Dim btBytesDecrypted() As Byte

    btBytesDecrypted = oEncryptDecrypt.TripleDESDecrypt(btBytesReturned, btKEK1,
    btInitVector)

    lstOutput.Items.Add("KCV 1 Decryption")

    lstOutput.Items.Add("3DES Decrypted CipherText: " &
    BitConverter.ToString(btBytesDecrypted))

    lstOutput.Items.Add("3DES Decrypted Text: " &
    Encoding.UTF8.GetString(btBytesDecrypted))

    lstOutput.Items.Add("KCV Returned : " &
    BitConverter.ToString(btBytesReturned))

    Catch exp As Exception

    HandleException(exp)

    End Try

    End Sub

    'Convert HEX to Byte Array

    Friend Function ConvertKEKFromHexToByteArray(ByVal sKEK As String) As Byte()

    'The Hex string needs to be broken into groups of two and then converted to
    ASCII

    Dim iHexLeft As Integer

    Dim iHexRight As Integer

    Dim sTempCharString As String

    Dim iCounter As Integer

    Dim iNoOfHexChars As Integer

    Dim btConvertedHex() As Byte

    Dim iArrayCounter As Integer

    'Extract all the "-" if they exist

    sKEK = sKEK.Replace("-", "")

    'Check that the string is in multiples of two

    If ((sKEK.Length Mod 2) = 0) Then

    iNoOfHexChars = CInt(sKEK.Length / 2)

    ReDim btConvertedHex(iNoOfHexChars - 1)

    Else

    Throw New ApplicationException("Invalid length of string")

    End If

    'Becasue the loop increments by 2 each time use another counter

    iArrayCounter = 0

    'Try reading the hex from left to right!

    For iCounter = 0 To (sKEK.Length - 1) Step 2

    sTempCharString = sKEK.Substring(iCounter, 2)

    iHexLeft = Uri.FromHex(CChar(sTempCharString.Substring(0, 1))) * 16

    iHexRight = Uri.FromHex(CChar(sTempCharString.Substring(1, 1)))

    Debug.WriteLine("Converted " & sTempCharString & " to int yields : " &
    iHexLeft + iHexRight)

    btConvertedHex(iArrayCounter) = iHexLeft + iHexRight

    iArrayCounter += 1

    Next

    Return btConvertedHex

    End Function

    Public Sub HandleException(ByVal exp As Exception)

    MsgBox("Exception Occurred" & vbCrLf & exp.Message & _

    vbCrLf & exp.GetType.ToString & vbCrLf & exp.Source & _

    vbCrLf & exp.StackTrace)

    End Sub

    End Class

    ********************************
    The class code
    ********************************
    Imports System

    Imports System.IO

    Imports System.Text

    Imports System.Security.Cryptography

    Friend Class clsEncryptDecrypt

    Private m_eCipherMode As CipherMode

    Private m_ePaddingMode As PaddingMode

    Public Sub New(ByVal eCipherMode As CipherMode, ByVal ePaddingMode As
    PaddingMode)

    m_eCipherMode = eCipherMode

    m_ePaddingMode = ePaddingMode

    End Sub

    'Overload that accepts the String to encrypt, the encryption key

    'and Init Vector as byte arrays

    Public Function DESEncrypt(ByVal btStringToEncrypt() As Byte, _

    ByVal btEncryptionKey() As Byte, ByVal btInitVector() As Byte) As Byte()

    Dim msEncrypt As New MemoryStream()

    Dim oTransformation As ICryptoTransform

    Dim oCryptoService As DESCryptoServiceProvider

    Dim oEncryptStream As CryptoStream

    'Create the DEs service provider

    oCryptoService = New DESCryptoServiceProvider()

    oCryptoService.Key = btEncryptionKey

    oCryptoService.IV = btInitVector

    'Set the Crypto provider mode

    oCryptoService.Mode = m_eCipherMode

    oCryptoService.Padding = m_ePaddingMode

    'Create the Transformation using the input key and Init Vector

    oTransformation = oCryptoService.CreateEncryptor(btEncryptionKey,
    btInitVector)

    'Create the encryption stream using the memory stream and the

    'create encryptor transformation

    oEncryptStream = New CryptoStream(msEncrypt, _

    oTransformation, CryptoStreamMode.Write)

    'encrypt writing to the encryptionstream which is the memory stream

    oEncryptStream.Write(btStringToEncrypt, 0, CInt(btStringToEncrypt.Length))

    'close the streams that has been opened

    oEncryptStream.Close()

    'Write out some useful info

    Debug.WriteLine("DES Encrypt called")

    Debug.WriteLine("Entered Text : " &
    BitConverter.ToString(btStringToEncrypt))

    Debug.WriteLine("Encrypted Cipher Text : " &
    BitConverter.ToString(msEncrypt.ToArray))

    'Return the byte array

    Return msEncrypt.ToArray()

    End Function

    'Overload that accepts the encryption key and Init Vector as byte arrays

    Public Function DESEncrypt(ByVal sStringToEncrypt As String, _

    ByVal btEncryptionKey() As Byte, ByVal btInitVector() As Byte) As Byte()

    Dim msEncrypt As New MemoryStream()

    Dim btStringToEncrypt() As Byte

    Dim oTransformation As ICryptoTransform

    Dim oCryptoService As DESCryptoServiceProvider

    Dim oEncryptStream As CryptoStream

    btStringToEncrypt = System.Text.Encoding.UTF8.GetBytes(sStringToEncrypt)

    'Create the DES service provider

    oCryptoService = New DESCryptoServiceProvider()

    oCryptoService.Key = btEncryptionKey

    oCryptoService.IV = btInitVector

    'Set the Crypto provider mode

    oCryptoService.Mode = m_eCipherMode

    oCryptoService.Padding = m_ePaddingMode

    'Create the Transformation using the input key and Init Vector

    oTransformation = oCryptoService.CreateEncryptor(btEncryptionKey,
    btInitVector)

    'Create the encryption stream using the memory stream and the

    'create encryptor transformation

    oEncryptStream = New CryptoStream(msEncrypt, _

    oTransformation, CryptoStreamMode.Write)

    'encrypt writing to the encryptionstream which is the memory stream

    oEncryptStream.Write(btStringToEncrypt, 0, CInt(btStringToEncrypt.Length))

    'Finish encoding the last block

    oEncryptStream.Flush()

    oEncryptStream.FlushFinalBlock()

    'close the streams that has been opened

    oEncryptStream.Close()

    'Write out some useful info

    Debug.WriteLine("DES Encrypt called")

    Debug.WriteLine("Entered Text : " &
    BitConverter.ToString(btStringToEncrypt))

    Debug.WriteLine("Encrypted Cipher Text : " &
    BitConverter.ToString(msEncrypt.ToArray))

    'Return the byte array

    Return msEncrypt.ToArray()

    End Function

    'Overload that accepts the encryption key and Init Vector as strings

    Public Function DESEncrypt(ByVal sStringToEncrypt As String, _

    ByVal sEncryptionKey As String, ByVal sInitVector As String) As Byte()

    Dim msEncrypt As New MemoryStream()

    Dim btStringToEncrypt() As Byte

    Dim btEncryptionKey() As Byte

    Dim btInitVector() As Byte

    Dim oTransformation As ICryptoTransform

    Dim oCryptoService As DESCryptoServiceProvider

    Dim oEncryptStream As CryptoStream

    btStringToEncrypt = System.Text.Encoding.UTF8.GetBytes(sStringToEncrypt)

    'Create the DEs service provider

    oCryptoService = New DESCryptoServiceProvider()

    'Set the Crypto provider mode

    oCryptoService.Mode = m_eCipherMode

    oCryptoService.Padding = m_ePaddingMode

    'Create the Transformation using the input key and Init Vector

    btEncryptionKey = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey)

    btInitVector = System.Text.Encoding.UTF8.GetBytes(sInitVector)

    oTransformation = oCryptoService.CreateEncryptor(btEncryptionKey,
    btInitVector)

    'Create the encryption stream using the memory stream and the

    'create encryptor transformation

    oEncryptStream = New CryptoStream(msEncrypt, _

    oTransformation, CryptoStreamMode.Write)

    'encrypt writing to the encryptionstream which is the memory stream

    oEncryptStream.Write(btStringToEncrypt, 0, CInt(btStringToEncrypt.Length))

    'close the streams that has been opened

    oEncryptStream.Close()

    'Write out some useful info

    Debug.WriteLine("DES Encrypt called")

    Debug.WriteLine("Entered Text : " &
    BitConverter.ToString(btStringToEncrypt))

    Debug.WriteLine("Encrypted Cipher Text : " &
    BitConverter.ToString(msEncrypt.ToArray))

    'Return the byte array

    Return msEncrypt.ToArray()

    End Function

    'Overload that accepts the encryption key and Init Vector as byte arrays

    Public Function DESDecrypt(ByVal btByteArrayToDecrypt As Byte(), _

    ByVal sEncryptionKey As String, ByVal sInitVector As String) As Byte()

    Dim msDecrypt As New MemoryStream()

    Dim btEncryptionKey() As Byte

    Dim btInitVector() As Byte

    Dim oTransformation As ICryptoTransform

    Dim oCryptoService As DESCryptoServiceProvider

    Dim oDecryptStream As CryptoStream

    'Create the DEs service provider

    oCryptoService = New DESCryptoServiceProvider()

    'Set the Crypto provider mode

    oCryptoService.Mode = m_eCipherMode

    oCryptoService.Padding = m_ePaddingMode

    'Create the Transformation using the input key and Init Vector

    btEncryptionKey = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey)

    btInitVector = System.Text.Encoding.UTF8.GetBytes(sInitVector)

    oTransformation = oCryptoService.CreateDecryptor(btEncryptionKey,
    btInitVector)

    'Create the encryption stream using the memory stream and the

    'create DECRYPTOR transformation

    oDecryptStream = New CryptoStream(msDecrypt, _

    oTransformation, CryptoStreamMode.Write)

    'Decrypt writing to the encryptionstream which is the underlying memory
    stream

    oDecryptStream.Write(btByteArrayToDecrypt, 0,
    CInt(btByteArrayToDecrypt.Length))

    'close the streams that has been opened

    oDecryptStream.Close()

    'Write out some useful info

    Debug.WriteLine("DES Decrypt called")

    Debug.WriteLine("Cipher Text : " &
    BitConverter.ToString(btByteArrayToDecrypt))

    Debug.WriteLine("Decrypted Text : " &
    BitConverter.ToString(msDecrypt.ToArray()))

    'return the memory stream to a byte array

    Return msDecrypt.ToArray()

    End Function

    'Overload that accepts the encryption key and Init Vector as byte arrays

    Public Function DESDecrypt(ByVal btByteArrayToDecrypt As Byte(), _

    ByVal btEncryptionKey() As Byte, ByVal btInitVector() As Byte) As Byte()

    Dim msDecrypt As New MemoryStream()

    Dim oTransformation As ICryptoTransform

    Dim oCryptoService As DESCryptoServiceProvider

    Dim oDecryptStream As CryptoStream

    'Create the DEs service provider

    oCryptoService = New DESCryptoServiceProvider()

    'Set the Crypto provider mode

    oCryptoService.Mode = m_eCipherMode

    oCryptoService.Padding = m_ePaddingMode

    'Create the Transformation using the input key and Init Vector

    oTransformation = oCryptoService.CreateDecryptor(btEncryptionKey,
    btInitVector)

    'Create the encryption stream using the memory stream and the

    'create DECRYPTOR transformation

    oDecryptStream = New CryptoStream(msDecrypt, _

    oTransformation, CryptoStreamMode.Write)

    'Decrypt writing to the encryptionstream which is the underlying memory
    stream

    oDecryptStream.Write(btByteArrayToDecrypt, 0,
    CInt(btByteArrayToDecrypt.Length))

    'Finish encoding the last block

    oDecryptStream.Flush()

    oDecryptStream.FlushFinalBlock()

    'close the streams that has been opened

    oDecryptStream.Close()

    'Write out some useful info

    Debug.WriteLine("DES Decrypt called")

    Debug.WriteLine("Cipher Text : " &
    BitConverter.ToString(btByteArrayToDecrypt))

    Debug.WriteLine("Decrypted Text : " &
    BitConverter.ToString(msDecrypt.ToArray()))

    'return the memory stream to a byte array

    Return msDecrypt.ToArray()

    End Function

    'Overload that accepts the encryption key and Init Vector as byte arrays

    Public Function TripleDESEncrypt(ByVal sStringToEncrypt As String, _

    ByVal btEncryptionKey() As Byte, ByVal btInitVector() As Byte) As Byte()

    Dim msEncrypt As New MemoryStream()

    Dim btStringToEncrypt() As Byte

    Dim oTransformation As ICryptoTransform

    Dim oCryptoService As TripleDESCryptoServiceProvider

    Dim oEncryptStream As CryptoStream

    btStringToEncrypt = System.Text.Encoding.UTF8.GetBytes(sStringToEncrypt)

    'Create the Triple DES service provider

    oCryptoService = New TripleDESCryptoServiceProvider()

    'Set the Crypto provider mode

    oCryptoService.Mode = m_eCipherMode

    oCryptoService.Padding = m_ePaddingMode

    'Create the Transformation using the input key and Init Vector

    oTransformation = oCryptoService.CreateEncryptor(btEncryptionKey,
    btInitVector)

    'Create the encryption stream using the memory stream and the

    'create encryptor transformation

    oEncryptStream = New CryptoStream(msEncrypt, _

    oTransformation, CryptoStreamMode.Write)

    'encrypt writing to the encryptionstream which is the memory stream

    oEncryptStream.Write(btStringToEncrypt, 0, CInt(btStringToEncrypt.Length))

    'close the streams that has been opened

    oEncryptStream.Close()

    'Write out some useful info

    Debug.WriteLine("3DES Encrypt called")

    Debug.WriteLine("Text Input : " & BitConverter.ToString(btStringToEncrypt))

    Debug.WriteLine("Encrypted Cipher Text : " &
    BitConverter.ToString(msEncrypt.ToArray))

    'Return the byte array

    Return msEncrypt.ToArray()

    End Function

    'Overload that accepts the encryption key and Init Vector as byte arrays

    Public Function TripleDESEncrypt(ByVal sStringToEncrypt As String, _

    ByVal sEncryptionKey As String, ByVal sInitVector As String) As Byte()

    Dim msEncrypt As New MemoryStream()

    Dim btStringToEncrypt() As Byte

    Dim btEncryptionKey() As Byte

    Dim btInitVector() As Byte

    Dim oTransformation As ICryptoTransform

    Dim oCryptoService As TripleDESCryptoServiceProvider

    Dim oEncryptStream As CryptoStream

    btStringToEncrypt = System.Text.Encoding.UTF8.GetBytes(sStringToEncrypt)

    'Create the DEs service provider

    oCryptoService = New TripleDESCryptoServiceProvider()

    'Set the Crypto provider mode

    oCryptoService.Mode = m_eCipherMode

    oCryptoService.Padding = m_ePaddingMode

    'Create the Transformation using the input key and Init Vector

    btEncryptionKey = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey)

    btInitVector = System.Text.Encoding.UTF8.GetBytes(sInitVector)

    oTransformation = oCryptoService.CreateEncryptor(btEncryptionKey,
    btInitVector)

    'Create the encryption stream using the memory stream and the

    'create encryptor transformation

    oEncryptStream = New CryptoStream(msEncrypt, _

    oTransformation, CryptoStreamMode.Write)

    'encrypt writing to the encryptionstream which is the memory stream

    oEncryptStream.Write(btStringToEncrypt, 0, CInt(btStringToEncrypt.Length))

    'close the streams that has been opened

    oEncryptStream.Close()

    'Write out some useful info

    Debug.WriteLine("3DES Encrypt called")

    Debug.WriteLine("Entered Text : " &
    BitConverter.ToString(btStringToEncrypt))

    Debug.WriteLine("Encrypted Cipher Text : " &
    BitConverter.ToString(msEncrypt.ToArray))

    'Return the byte array

    Return msEncrypt.ToArray()

    End Function

    'Overload that accepts the encryption key and Init Vector as byte arrays

    Public Function TripleDESDecrypt(ByVal btByteArrayToDecrypt As Byte(), _

    ByVal btEncryptionKey() As Byte, ByVal btInitVector() As Byte) As Byte()

    Dim msDecrypt As New MemoryStream()

    Dim oTransformation As ICryptoTransform

    Dim oCryptoService As TripleDESCryptoServiceProvider

    Dim oDecryptStream As CryptoStream

    'Create the DEs service provider

    oCryptoService = New TripleDESCryptoServiceProvider()

    'Set the Crypto provider mode

    oCryptoService.Mode = m_eCipherMode

    oCryptoService.Padding = m_ePaddingMode

    'Create the Transformation using the input key and Init Vector

    oTransformation = oCryptoService.CreateDecryptor(btEncryptionKey,
    btInitVector)

    'Create the encryption stream using the memory stream and the

    'create DECRYPTOR transformation

    oDecryptStream = New CryptoStream(msDecrypt, _

    oTransformation, CryptoStreamMode.Write)

    'Decrypt writing to the encryptionstream which is the underlying memory
    stream

    oDecryptStream.Write(btByteArrayToDecrypt, 0,
    CInt(btByteArrayToDecrypt.Length))

    'close the streams that has been opened

    oDecryptStream.Close()

    'Write out some useful info

    Debug.WriteLine("Triple DES Decrypt called")

    Debug.WriteLine("Cipher Text : " &
    BitConverter.ToString(btByteArrayToDecrypt))

    Debug.WriteLine("Decrypted Text : " &
    BitConverter.ToString(msDecrypt.ToArray()))

    'return the memory stream to a byte array

    Return msDecrypt.ToArray()

    End Function

    Public Sub TestThisCode(ByVal lstRefToListBox As
    System.Windows.Forms.ListBox, _

    ByVal sStringToencrypt As String, ByVal sEncryptionKey As String, _

    ByVal sInitVector As String)

    Dim btEncryptedString() As Byte

    Dim btDecryptedString() As Byte

    btEncryptedString = DESEncrypt(sStringToencrypt, sEncryptionKey,
    sInitVector)

    btDecryptedString = DESDecrypt(btEncryptedString, sEncryptionKey,
    sInitVector)

    'Display the hex values of the byte array

    lstRefToListBox.Items.Add("Start values")

    lstRefToListBox.Items.Add(vbTab & "String to Encrypt - " & sStringToencrypt)

    lstRefToListBox.Items.Add(vbTab & "Encryption key - " & sEncryptionKey)

    lstRefToListBox.Items.Add(vbTab & "Init Vector - " & sInitVector)

    lstRefToListBox.Items.Add("Encrypted data: " +
    BitConverter.ToString(btEncryptedString))

    lstRefToListBox.Items.Add("Decrypted data: " +
    BitConverter.ToString(btDecryptedString))

    lstRefToListBox.Items.Add("Decrypted text: " +
    System.Text.Encoding.UTF8.GetString(btDecryptedString))

    End Sub

    End Class

    ********************************

    "Ivan Medvedev [MS]" <ivanmed@online.microsoft.com> wrote in message
    news:#laC6zgKDHA.1612@TK2MSFTNGP11.phx.gbl...
    > Dean -
    > please check that you are feeding to the decryptor all the data you have
    > received on the encryption phase. Normally a cipher text is skightly
    longer
    > that the plain text and it is a very common mistake when people are
    feeding
    > the number of bytes the plaintext had to the decryptor. If this is not the
    > case in your implementation please post some code.
    > Thanks,
    > --Ivan
    > This posting is provided "AS IS" with no warranties, and confers no
    rights.
    >
    >
    > "dean" <abc@def.com> wrote in message
    > news:eL%23H1ZFJDHA.1732@TK2MSFTNGP11.phx.gbl...
    > > Hi all,
    > >
    > > Is anyone familiar with the AnsiX9.19 document which handles the
    > generation
    > > of Key Encryption Keys (KEK) and Key Check Vaues (KCV). A rough overview
    > of
    > > the process is as follows:
    > >
    > > Step 1 : Take a given 128bit key, and divide it into 2 - to generate key
    > > parts KL equals the left 64 bits and KR the right.
    > > Step 2 : Then encrypt the number zero "0" using the left hand key part
    > (KL)
    > > and DES.
    > > Step 3 : The output of step 2 is then decrypted using the right hand key
    > > part (KR).
    > > Step 4 : The final step is to re-encrypt this output using the left hand
    > key
    > > part once again.
    > >
    > > According to the ANSI doc this yields a Key Check Value which can be
    used
    > > for message authentication.
    > >
    > > The Step 1 encryption part works fine but Step 2 decrypting using the
    > right
    > > hand key part fails with the infamous 'Bad Data' cryptographic
    exception.
    > > When I reran the process using the the left hand key part (KL) for both
    > > encryption, decryption and the re-encryption it works fine. This leads
    me
    > to
    > > beleive that the code is ok but the decryption process doesn't like a
    > > different key.
    > >
    > > Does any one have any ideas on this. Help would be greatly appreciated.
    > >
    > > Best regards
    > >
    > > Dean
    > >
    > > PS I can attach some code samples if that would help.
    > >
    > >
    >
    >


  • Next message: Etienne Charland: "Re: user rights of the logged in user in .net"