Re: Datatable Column ByteArray Problem
- From: "Phil C." <charlestek@xxxxxxx>
- Date: Sat, 10 Dec 2005 10:31:22 -0500
Cor,
There is no problem with decryption,
the decryption code works fine independently, and indeed does use memory
streams.
'--------------------------Function Encrypt---------------------------
Friend Overloads Function Encrypt(ByVal plainText As String) As Byte()
'Declare a UTF8Encoding object so that we can use the GetByte
'method to transform the plain Text into a Byte Array
'Dim utf8encoder As New UTF8Encoding
Dim inputInBytes() As Byte = Encoding.UTF8.GetBytes(plainText)
'Create a new AES Service Provider
Dim aesProvider As New RijndaelManaged
'Declare the key size
aesProvider.KeySize = 256
aesProvider.BlockSize = 256
'Set the aes key
aesProvider.Key() = _key
'----------Generate a new IV each time the encrypt function is called:
aesProvider.GenerateIV()
_encryptInitVector = aesProvider.IV
'The ICryptTransform interface uses the Aes crypt provider along with
'encryption key and initialization vector info
'Generate an ICryptoTransform object with the provider create encryptor
Dim cryptoTransform As ICryptoTransform = aesProvider.CreateEncryptor()
' Crypto functions need a stream to output the encrypted info.
'We want to use a memory stream
Dim encryptedStream As New MemoryStream
Dim cryptStream As New CryptoStream(encryptedStream, cryptoTransform,
CryptoStreamMode.Write)
'Write the encrypted information to he stream. Flush the information
'When done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
'Read the stream back into a byte array and return it
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
Friend Overloads Function Encrypt(ByVal plainText As String, ByVal iV As
Byte()) As Byte()
'Declare a UTF8Encoding object so that we can use the GetByte
'method to transform the plain Text into a Byte Array
'Dim utf8encoder As New UTF8Encoding
Dim inputInBytes() As Byte = Encoding.UTF8.GetBytes(plainText)
'Create a new AES Service Provider
Dim aesProvider As New RijndaelManaged
'Declare the key size
aesProvider.KeySize = 256
aesProvider.BlockSize = 256
'Get the aes key from the config handler
'Set the aes key
aesProvider.Key() = _key
'Use the iv Passed in as a parameter
_encryptInitVector = iV
'The ICryptTransform interface uses the Aes crypt provider along with
'encryption key and initialization vector info
'Generate an ICryptoTransform object with the provider create encryptor
Dim cryptoTransform As ICryptoTransform = aesProvider.CreateEncryptor()
' Crypto functions need a stream to output the encrypted info.
'We want to use a memory stream
Dim encryptedStream As New MemoryStream
Dim cryptStream As New CryptoStream(encryptedStream, cryptoTransform,
CryptoStreamMode.Write)
'Write the encrypted information to he stream. Flush the information
'When done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
'Read the stream back into a byte array and return it
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
'---------------------------End Function Encrypt
'----------------------------Function Decrypt
Friend Function Decrypt(ByVal inputInBytes() As Byte, ByVal iVInBytes() As
Byte) As String
'UTFEncoding is used to transform the decrypted Byte Array
'information back into a string.
'Dim utf8encoder As New UTF8Encoding
Dim aesProvider As New RijndaelManaged
'Declare the key size and block size
aesProvider.KeySize = 256
aesProvider.BlockSize = 256
'Get the Aes Key
Dim aesKeyBytes() As Byte = _key
'Get the crypto transform object from the provider given the
'key and iv vector
Dim cryptoTransform As ICryptoTransform =
aesProvider.CreateDecryptor(aesKeyBytes, iVInBytes)
'Provide memory stream
Dim decryptedStream As New MemoryStream
Dim cryptStream As New CryptoStream(decryptedStream, cryptoTransform,
CryptoStreamMode.Write)
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
decryptedStream.Position = 0
'Read the memory stream and convert it back to a string
Dim result(decryptedStream.Length - 1) As Byte
decryptedStream.Read(result, 0, decryptedStream.Length)
cryptStream.Close()
'Dim myUTF As New UTF8Encoding
Return Encoding.UTF8.GetString(result)
End Function
End Class
"Cor Ligthert [MVP]" <notmyfirstname@xxxxxxxxx> wrote in message
news:OPz0EtW$FHA.1408@xxxxxxxxxxxxxxxxxxxxxxx
> Phil,
>
> I hate decrypting problems, however I have the idea that you at least miss
> the streaming, for which you can use to avoid a disk the memorystream.
>
> http://msdn2.microsoft.com/en-us/library/system.io.memorystream.aspx
>
> I answered it because I saw no answers so don't expect much help from this
> beside this.
>
> Cor
>
>
> "Phil C." <charlestek@xxxxxxx> schreef in bericht
> news:eqE0T2O$FHA.3136@xxxxxxxxxxxxxxxxxxxxxxx
>> I've been having trouble getting a byte array back as a datatable column
>> with this code:
>> Public Class RegisteredCustomerVerify
>> ''' -----------------------------------------------------------------------------
>> ''' <summary>
>> ''' Friend Function ValidEmail
>> ''' Pass plaintext email address to stored proc that must use
>> ''' aes key and decrypt each row of customer table and compare the
>> ''' email address to the passed email
>> ''' </summary>
>> ''' <param name="plaintextEmailAddress"></param>
>> ''' <returns>Returns True (email match) or False (no Email
>> match)</returns>
>> ''' <remarks>
>> ''' </remarks>
>> ''' <history>
>> ''' [SmallFry] 9/17/2005 Created
>> ''' </history>
>> ''' -----------------------------------------------------------------------------
>> Friend Function IfRegistered(ByVal plaintextEmailAddress As String,
>> ByVal pass As String) As Boolean
>> Dim custDs As New DataSet
>> 'custDs = SqlHelper.ExecuteDataset(connectionString(),
>> CommandType.StoredProcedure, "GetCustomerTable")
>> Dim cn As New SqlConnection(connectionString())
>> Dim cmd As New SqlDataAdapter
>> cmd.SelectCommand = New SqlCommand
>> With cmd.SelectCommand
>> .Connection = cn
>> .CommandText = "GetCustomerTable"
>> .CommandType = CommandType.StoredProcedure
>> End With
>> cmd.Fill(custDs, "Customers")
>> Dim dRow As DataRow
>> Dim dCol As DataColumn
>> Dim aes As New AesCryptClass
>> Dim iVByteArray As Byte()
>> Dim emailAddressByteArray() As Byte
>> Dim decryptedEmailAddress As String
>> Dim passByteArray() As Byte
>> Dim saltHsh As New SaltedHash
>> For Each dRow In custDs.Tables.Item(0).Rows
>> 'Get the IV value and the encrypted email value of each row
>> If Not (dRow("IV").Equals(System.DBNull.Value) And
>> dRow("EmailAddress").Equals(System.DBNull.Value)) Then
>>
>> 'Dim ivSqlBinary As New SqlBinary(dRow("IV"))
>> Dim type As Type = dRow.Table.Columns("IV").DataType()
>> type.ToString()
>> iVByteArray = dRow("IV")
>> emailAddressByteArray =
>> Encoding.UTF8.GetBytes(dRow("EmailAddress"))
>> passByteArray = Encoding.UTF8.GetBytes(dRow("Password"))
>> decryptedEmailAddress = aes.Decrypt(emailAddressByteArray,
>> iVByteArray)
>> If plaintextEmailAddress = decryptedEmailAddress And _
>> saltHsh.ComparePasswords(passByteArray,
>> Encoding.UTF8.GetBytes(pass)) Then
>> Return True
>> End If
>> End If
>> Next
>> Return False
>> End Function
>>
>>
>> In the debugger (code in asterisked section below), I am getting the
>> table "item" as <cannot view indexed property>
>> which led me to read this article:
>> http://dotnet247.com/247reference/msgs/17/86113.aspx
>> which states:
>>
>> Mark Miller
>> There's a subtle problem with your code. The Rows property of a
>> DataTable
>> returns a DataRowCollection, not a DataRow. The indexer you are
>> attempting
>> to use ([0, DataRowVersion.Current]) only exists in DataRow. Further
>> this
>> indexer returns an object, as in row["columnName"] (ie. a column
>> value), not
>> a DataRow.
>>
>> The only indexer in DataRowCollection is DataRow this[int index]
>> {get;}.
>>
>> So, the correct way to write your code would be:
>>
>> string fieldValue = updateDataSet.Tables[0].Rows[0][0,
>> DataRowVersion.Current];
>>
>> This will return the current version of the value in the first
>> column, in
>> the first row, of the first table.
>>
>> --
>>
>> ---Mark
>>
>>
>>
>> but I think I am doing it correctly.
>>
>> Any ideas would be appreciated.
>>
>>
>> Below is the expanded tree from my debugger window on the datatable:
>>
>> ******************************************************************
>> - custDs {System.Data.DataSet} System.Data.DataSet
>> CaseSensitive False Boolean
>> Container Nothing System.ComponentModel.IContainer
>> DataSetName "NewDataSet" String
>> + DefaultViewManager {System.Data.DataViewManager}
>> System.Data.DataViewManager
>> DesignMode False Boolean
>> EnforceConstraints True Boolean
>> + ExtendedProperties {System.Data.PropertyCollection}
>> System.Data.PropertyCollection
>> HasErrors False Boolean
>> + Locale {System.Globalization.CultureInfo}
>> System.Globalization.CultureInfo
>> Namespace "" String
>> Prefix "" String
>> + Relations
>> {System.Data.DataRelationCollection.DataSetRelationCollection}
>> System.Data.DataRelationCollection
>> Site Nothing System.ComponentModel.ISite
>> - Tables {System.Data.DataTableCollection}
>> System.Data.DataTableCollection
>> Count 1 Integer
>> IsReadOnly False Boolean
>> IsSynchronized False Boolean
>> Item <cannot view indexed property> System.Data.DataTable
>> - SyncRoot {System.Data.DataTableCollection} Object
>> - [System.Data.DataTableCollection] {System.Data.DataTableCollection}
>> System.Data.DataTableCollection
>> Count 1 Integer
>> IsReadOnly False Boolean
>> IsSynchronized False Boolean
>> Item <cannot view indexed property> System.Data.DataTable
>> - SyncRoot {System.Data.DataTableCollection} Object
>> - [System.Data.DataTableCollection] {System.Data.DataTableCollection}
>> System.Data.DataTableCollection
>> Count 1 Integer
>> IsReadOnly False Boolean
>> IsSynchronized False Boolean
>> Item <cannot view indexed property> System.Data.DataTable
>> - SyncRoot {System.Data.DataTableCollection} Object
>> - [System.Data.DataTableCollection] {System.Data.DataTableCollection}
>> System.Data.DataTableCollection
>> Count 1 Integer
>> IsReadOnly False Boolean
>> IsSynchronized False Boolean
>> Item <cannot view indexed property> System.Data.DataTable
>> - SyncRoot {System.Data.DataTableCollection} Object
>> - [System.Data.DataTableCollection] {System.Data.DataTableCollection}
>> System.Data.DataTableCollection
>> Count 1 Integer
>> IsReadOnly False Boolean
>> IsSynchronized False Boolean
>> Item <cannot view indexed property> System.Data.DataTable
>> - SyncRoot {System.Data.DataTableCollection} Object
>> - [System.Data.DataTableCollection] {System.Data.DataTableCollection}
>> System.Data.DataTableCollection
>> Count 1 Integer
>> IsReadOnly False Boolean
>> IsSynchronized False Boolean
>> Item <cannot view indexed property> System.Data.DataTable
>> - SyncRoot {System.Data.DataTableCollection} Object
>> + [System.Data.DataTableCollection] {System.Data.DataTableCollection}
>> System.Data.DataTableCollection
>> <cannot view indexed property> Expression expected.
>> + custDs.Tables {System.Data.DataTableCollection}
>> System.Data.DataTableCollection
>> *********************************************************************************************
>>
>>
>>
>>
>>
>>
>>
>
>
.
- References:
- Datatable Column ByteArray Problem
- From: Phil C.
- Re: Datatable Column ByteArray Problem
- From: Cor Ligthert [MVP]
- Datatable Column ByteArray Problem
- Prev by Date: Re: Using Connection Class VS Connection Module in Asp.net Application
- Next by Date: Re: Datatable Column ByteArray Problem
- Previous by thread: Re: Datatable Column ByteArray Problem
- Next by thread: Re: Datatable Column ByteArray Problem
- Index(es):
Relevant Pages
|