Clear IntPtr target in VB.NET - asp.net

I'm getting the error There is insufficient system memory in resource pool 'internal' to run this query. I've alread checked out this post: There is insufficient system memory in resource pool 'default' to run this query. on sql
However, the error occurs when I added the following code (also see ASP.NET libwebp.dll how to save WebP image to disk):
As you can see below WebPFree doesn't clear the memory reserved by the variable of type IntPtr. I'm not sure what code should be added in WebPFree and how to clear the used memory.
I also checked this post, but found no solution either.
Dim imgRequest As WebRequest = WebRequest.Create(imageURL)
Dim imgResponse As WebResponse
Dim memStream As New MemoryStream
imgResponse = imgRequest.GetResponse()
Dim streamPhoto As Stream = imgResponse.GetResponseStream()
streamPhoto.CopyTo(memStream)
memStream.Position = 0
Dim bfPhoto As BitmapFrame = ReadBitmapFrame(memStream)
Dim baResize As Byte() = ToByteArray(bfPhoto)
Dim bmp As System.Drawing.Bitmap = imageFunctions.ConvertByteArrayToBitmap(baResize)
File.WriteAllBytes(test.webp, imageFunctions.EncodeImageToWebP(bmp))
Public Class imageFunctions
<DllImport("libwebp.dll", CallingConvention:=CallingConvention.Cdecl)>
Public Shared Function WebPEncodeBGRA(ByVal rgba As IntPtr, ByVal width As Integer, ByVal height As Integer, ByVal stride As Integer, ByVal quality_factor As Single, <Out> ByRef output As IntPtr) As Integer
End Function
<DllImport("libwebp.dll", CallingConvention:=CallingConvention.Cdecl)>
Public Shared Function WebPFree(ByVal p As IntPtr) As Integer
End Function
Public Shared Function EncodeImageToWebP(ByVal img As System.Drawing.Bitmap) As Byte()
Dim bmpData As BitmapData = img.LockBits(New Drawing.Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
'Create a pointer for webp data
Dim webpDataSrc As IntPtr
'Store resulting webp data length after conversion
Dim webpDataLen As Integer = WebPEncodeBGRA(bmpData.Scan0, img.Width, img.Height, bmpData.Stride, 80, webpDataSrc)
'Create a managed byte array with the size you just have
Dim webpDataBin As Byte() = New Byte(webpDataLen - 1) {}
'Copy from unmanaged memory to managed byte array you created
System.Runtime.InteropServices.Marshal.Copy(webpDataSrc, webpDataBin, 0, webpDataLen)
'Free
WebPFree(webpDataSrc)
img.Dispose()
img.UnlockBits(bmpData)
Return webpDataBin
End Function
Public Shared Function ConvertByteArrayToBitmap(ByVal imageData As Byte()) As System.Drawing.Bitmap
Dim ms As New IO.MemoryStream(imageData)
Return New Drawing.Bitmap(ms)
End Function
End Class

Related

ASP.NET: Unable to cast IO.StreamWriter to IO.MemoryStream

I have a complex class module that make a lot of processing and return a object of type IO.StreamWriter, but I need cast this object to IO.MemoryStream, furthemore to Byte(). Finally it converts Byte() to Base64String that ajax consumes and generate a CSV file.
I made this with DynamicPDF.Document, but this library has a method that returns binary.
Dim objSW As IO.StreamWriter = EXP.ExportarBinario(objCommand, HttpContext.Current.Response.OutputStream, 1)
Dim objMS As New MemoryStream()
objSW.BaseStream.CopyTo(objMS)
Dim objArrayByte As Byte() = objMS.ToArray()
Dim strArrayByte64 As String = String.Format("data:{0};base64,{1}", "application/vnd.excel", Convert.ToBase64String(objArrayByte))
Return strArrayByte64

Implementing an Image Download in VB.NET

I am trying to implement an image download in vb.net where the client clicks a button and the browser downloads an image for the client from a file in the server.
I tried this:
Private Sub DownloadImage(ByVal ImageURL As String)
Dim Buffer(6000000) As Byte
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=" & ImageURL & ".jpg")
Response.ContentType = "image/jpeg"
Response.BinaryWrite(Buffer)
Response.Flush()
Response.End()
End Sub
But this has 2 problems. First, it doesn't actually show up the image when I download it so it doesn't work properly. Secondly I have to manually enter the size of the image to determine the size of the byte array.
Please help me out, I couldn't find any resources on internet and couldn't get my head around it.
Thanks!
This is a sample image handler I've used for several years. It's probably got some room for improvement, but it is intended to be used as the src attribute for an img tag.
<img src="Thumbs.ashx?img=/ImagePath/BigImage.jpg&max=100" />
It's a direct copy-paste of my working code and it's got some references to private code - but it should give you a good start. It will create a thumbnail image so it doesn't have to be regenerated each time, if the thumbnail has already been generated. Hope this helps...
<%# WebHandler Language="VB" Class="GetImage" %>
Imports Web.Utilities
Imports Common
Imports System
Imports System.Drawing
Imports System.Web
Imports System.IO
''' <summary>
''' Resizes the image supplied in the "img" querystring parameter and writes it to the OutputStream in jpg format.
''' The default dimension is a max of 90 pixels (H or W; whichever is larger).
''' The "max" querystring parameter can alter the maximum dimension by supplying a new dimension as an integer.
''' If the file name contains an ampersand, it should be replaced with [amp].
''' </summary>
''' <remarks></remarks>
Public Class GetImage : Implements IHttpHandler
Private thumbFolder As String = "/images/Thumbs/"
Private trapCount As Integer = 0
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'General.PreventClientCaching()
'context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim maxSize As Integer = 90
Dim img As String = context.Request.QueryString("img")
Dim strMax As String = context.Request.QueryString("max")
If Not strMax.IsNullOrEmpty AndAlso IsNumeric(strMax) Then
maxSize = CInt(strMax)
End If
If maxSize > 1000 Then
maxSize = 1000
End If
If img.IsNullOrEmpty Then
img = "/images/PicUnavailable.jpg"
End If
Try
Dim uri As New System.Uri(img, UriKind.RelativeOrAbsolute)
img = uri.AbsolutePath
Catch ex As Exception
End Try
General.SetContentType(General.FileType.Jpg)
img = img.Replace("[amp]", "&")
ServeImage(context, img, maxSize)
End Sub
Private Sub ServeImage(ByVal context As HttpContext, ByVal imagePath As String, ByVal maximumSize As Integer)
Dim imgFile As Image = Nothing
Dim existingThumb As String = imagePath.Replace("/", "{s}") & "_" & maximumSize.ToString & ".jpg"
Dim doPurge As Boolean
Boolean.TryParse(context.Request.QueryString("purge"), doPurge)
' Check to see if the thumbnail has already been generated and it's older than the source.
' If it is, delete it.
If File.Exists(context.Server.MapPath(thumbFolder & existingThumb)) Then
If doPurge Then
File.Delete(context.Server.MapPath(thumbFolder & existingThumb))
Else
If File.GetLastWriteTime(context.Server.MapPath(thumbFolder & existingThumb)) < File.GetLastWriteTime(context.Server.MapPath(imagePath)) Then
Try
File.Delete(context.Server.MapPath(thumbFolder & existingThumb))
Catch ex As Exception
End Try
End If
End If
End If
' If the thumbnail already exists, write the byte array to the output stream
If File.Exists(context.Server.MapPath(thumbFolder & existingThumb)) Then
Dim fs As FileStream = Nothing
Try
fs = New FileStream(context.Server.MapPath(thumbFolder & existingThumb), IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim imgLen As Long = fs.Length()
Dim imgData(imgLen) As Byte
fs.Read(imgData, 0, Integer.Parse(imgLen.ToString()))
context.Response.OutputStream.Write(imgData, 0, Integer.Parse(imgLen.ToString()))
Catch ex2 As UnauthorizedAccessException
'context.Server.Transfer(img)
Throw
Catch exIO As IOException
'context.Server.Transfer(img)
Throw
Finally
If Not fs Is Nothing Then
fs.Dispose()
fs = Nothing
End If
End Try
' the file doesn't exist, so render it to the output stream and save it to the thumbnail
Else
Try
imgFile = Image.FromFile(context.Server.MapPath(imagePath))
Dim maxDim As Integer = maximumSize
Dim maxH As Integer = maximumSize
Dim maxW As Integer = maximumSize
'If img.Height > maxH OrElse img.Width > maxW Then
Dim thumb As Image
Dim gfx As Graphics
Dim rect As Rectangle
If imgFile.Height >= imgFile.Width Then 'portrait or square
Dim newW As Integer
newW = CInt((maxH / imgFile.Height) * imgFile.Width)
thumb = New Bitmap(newW, maxDim)
gfx = Graphics.FromImage(thumb)
gfx.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
gfx.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
gfx.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
rect = New Rectangle(0, 0, newW, maxDim)
Else 'landscape
Dim newH As Integer
newH = CInt((maxW / imgFile.Width) * imgFile.Height)
thumb = New Bitmap(maxDim, newH)
gfx = Graphics.FromImage(thumb)
gfx.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
gfx.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
gfx.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
rect = New Rectangle(0, 0, maxDim, newH)
End If
gfx.DrawImage(imgFile, rect)
thumb.Save(context.Response.OutputStream, Drawing.Imaging.ImageFormat.Jpeg)
thumb.Save(context.Server.MapPath(thumbFolder & existingThumb), Drawing.Imaging.ImageFormat.Jpeg)
gfx.Dispose()
thumb.Dispose()
gfx = Nothing
thumb = Nothing
Catch ex As Exception
Dim fs As FileStream = Nothing
Try
fs = New FileStream(context.Server.MapPath(imagePath), IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim imgLen As Long = fs.Length()
Dim imgData(imgLen) As Byte
fs.Read(imgData, 0, Integer.Parse(imgLen.ToString()))
context.Response.OutputStream.Write(imgData, 0, Integer.Parse(imgLen.ToString()))
Catch ex2 As UnauthorizedAccessException
'context.Server.Transfer(img)
Throw
Catch exIO As IOException
'context.Server.Transfer(img)
If trapCount > 0 Then
Throw
End If
trapCount += 1
ServeImage(context, "/images/PicUnavailable.jpg", maximumSize)
Finally
If Not fs Is Nothing Then
fs.Dispose()
fs = Nothing
End If
End Try
Finally
If Not imgFile Is Nothing Then
imgFile.Dispose()
imgFile = Nothing
End If
End Try
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Converting image into stream

I'm using a function that uploads an image, takes the stream and resizes it using imageresizer.net, then uploads the stream to Amazon S3.
Now I want to take a local picture and convert it into a stream. (to resize and upload to amazonS3). Basically, how do you convert an image into a stream.
This might be a simple question, just could not find the answer anywhere.
Here is some basic code.
Public Shared Sub MoveToAmazon(strImg As String, SKU As String)
Dim fullImg As String = "C:\ImageLocation\" & strImg
Dim img As Image = Image.FromFile(fullImg)
'Here Im missing the code to convert it to a stream.
UploadImage(imgStream, SKU)
End Sub
Public Shared Sub UploadImage(imgStream As Stream, imgName As String)
Dim MainStream As Stream = New MemoryStream
Dim HomeStream As Stream = New MemoryStream
Dim SmallStream As Stream = New MemoryStream
Dim TinyStream As Stream = New MemoryStream
Dim MidStream As Stream = New MemoryStream
Dim GridStream As Stream = New MemoryStream
Dim ListStream As Stream = New MemoryStream
Dim c As New ImageResizer.Configuration.Config
Dim SourceImage As Bitmap = New Bitmap(imgStream)
Dim SourceMain As Bitmap = New Bitmap(SourceImage)
Dim SourceHome As Bitmap = New Bitmap(SourceImage)
Dim SourceSmall As Bitmap = New Bitmap(SourceImage)
Dim SourceTiny As Bitmap = New Bitmap(SourceImage)
Dim SourceMid As Bitmap = New Bitmap(SourceImage)
Dim SourceGrid As Bitmap = New Bitmap(SourceImage)
Dim SourceList As Bitmap = New Bitmap(SourceImage)
ImageResizer.ImageBuilder.Current.Build(SourceMain, MainStream, New ResizeSettings("width=300&height=372&scale=both&paddingWidth=40")) 'ProductPage
ImageResizer.ImageBuilder.Current.Build(SourceHome, HomeStream, New ResizeSettings("width=112&height=147&scale=both")) 'HomePage Products
ImageResizer.ImageBuilder.Current.Build(SourceGrid, GridStream, New ResizeSettings("width=149&height=149&scale=both")) 'Categories Grid
ImageResizer.ImageBuilder.Current.Build(SourceList, ListStream, New ResizeSettings("width=171&height=206&scale=both")) 'Categories List
ImageResizer.ImageBuilder.Current.Build(SourceSmall, SmallStream, New ResizeSettings("width=64&height=75&scale=both")) 'Accessories
ImageResizer.ImageBuilder.Current.Build(SourceTiny, TinyStream, New ResizeSettings("width=82&height=82&scale=both")) 'Cart
ImageResizer.ImageBuilder.Current.Build(SourceMid, MidStream, New ResizeSettings("width=155&height=116&scale=both")) 'CategoryMain
AmazonUploadFile("OriginalImages/" & imgName, imgStream)
AmazonUploadFile("MainImages/" & imgName, MainStream)
AmazonUploadFile("HomeImages/" & imgName, HomeStream)
AmazonUploadFile("GridImages/" & imgName, GridStream)
AmazonUploadFile("ListImages/" & imgName, ListStream)
AmazonUploadFile("SmallImages/" & imgName, SmallStream)
AmazonUploadFile("TinyImages/" & imgName, TinyStream)
AmazonUploadFile("MidImages/" & imgName, MidStream)
End Sub
Public Shared Sub AmazonUploadFile(S3Key As String, FileStream As Stream)
Dim request As New PutObjectRequest()
request.WithBucketName(BUCKET_NAME)
request.WithKey(S3Key).InputStream = FileStream
request.WithCannedACL(S3CannedACL.PublicRead)
GetS3Client.PutObject(request)
End Sub
[Disclaimer - I'm the author of the ImageResizing.NET library the OP is asking the question about.]
Folks - do NOT use Bitmap and Image instances if you can possibly avoid it. There is a giant list of pitfalls that will crash your server. Do NOT use ANYTHING from System.Drawing without a server-safe wrapper around it.
#dash - Your code is almost right, aside from the memory leaks.
Decoding and encoding images safely isn't straightforward. Let the ImageResizing.Net library handle it.
Dim settings as New ResizeSettings("width=64&height=75&scale=both")
Using ms As New MemoryStream()
ImageBuilder.Current.Build("C:\ImageLocation\" & strImg, ms, settings)
ms.Seek(0, SeekOrigin.Begin)
UploadImage(ms, SKU)
End Using
Never load something into a Bitmap or Image instance if you're making multiple versions. Clone the file into a MemoryStream instead.
Using fs as New FileStream(...)
Using ms as MemoryStream = Util.StreamUtils.CopyStream(fs)
'For loop here with your setting variations
ms.Seek(0, SeekOrigin.Begin)
'Place upload and resize code here
'End Loop
End Using
End Using
The following code snippet should do what you want:
Using myImage = Image.FromFile(fullImg)
Using ms As New MemoryStream()
myImage.Save(ms, ImageFormat.Jpeg)
ms.Seek(0, SeekOrigin.Begin)
UploadImage(ms, SKU)
End Using
End Using
As an aside, you might find it easier to parameterize your methods and do all the work when calling them. Something like the following may make your life easier (this assumes the code you posted is code you are actually using and not a demo):
Public Shared Sub UploadImages()
'Call this for each image
MoveToAmazon("C:\ImageLocation\blah.jpg", "OriginalImage", 300, 300, 0, "whatever")
End Sub
Public Shared Sub MoveToAmazon(strImg As String, targetFolder As String, height as Integer, width as Integer, padding as Integer, SKU As String)
Dim fullImg As String = "" & strImg
Using img = Image.FromFile(fullImg)
'Here Im missing the code to convert it to a stream.
Using ms As New MemoryStream()
Image.Save(ms, ImageFormat.Jpeg)
ms.Seek(0, SeekOrigin.Begin)
UploadImage(ms, SKU)
End Using
End Using
End Sub
Public Shared Sub UploadImage(imgStream As Stream, imgName As String, targetFolder As String, height as Integer, width as Integer, padding as Integer, SKU As String)
Dim c As New ImageResizer.Configuration.Config
ImageResizer.ImageBuilder.Current.Build(SourceMain, imgStream, New ResizeSettings("width=" & CStr(width) & "&height=" & CStr(height) & "&scale=both&paddingWidth=" & CStr(padding))
AmazonUploadFile(targetFolder & "/" & imgName, imgStream)
End Sub
Public Shared Sub AmazonUploadFile(S3Key As String, FileStream As Stream)
Dim request As New PutObjectRequest()
request.WithBucketName(BUCKET_NAME)
request.WithKey(S3Key).InputStream = FileStream
request.WithCannedACL(S3CannedACL.PublicRead)
GetS3Client.PutObject(request)
End Sub
Using ms As New MemoryStream()
Image.Save(ms, ImageFormat.Jpeg)
ms.Seek(0, SeekOrigin.Begin)
UploadImage(ms, SKU)
End Using
Read the image bytes and then you wrap it in a MemoryStream
MemoryStream ms = new MemoryStream(imageBytes);

CryptoStream.FlushFinalBlock throwing input data is not a complete block exception

I use the following two methods to encrypt and decrypt strings:
'Encrypts string. Returns encrypted byte array.
Public Function Encrypt(ByVal str As String) As Byte()
Dim inputInBytes() As Byte = Encoding.Unicode.GetBytes(str)
Dim laesProvider As New AesCryptoServiceProvider()
laesProvider.Key = _key
laesProvider.Mode = CipherMode.CBC
laesProvider.IV = _IV
laesProvider.Padding = PaddingMode.PKCS7
Dim lencryptor As ICryptoTransform = laesProvider.CreateEncryptor
Dim encryptedStream As New MemoryStream
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, lencryptor, CryptoStreamMode.Write)
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
'Decrypts bytearray. Returns string.
Public Function DecryptToStr(ByVal inputInBytes() As Byte) As String
Dim laesProvider As New AesCryptoServiceProvider()
laesProvider.Key = _key
laesProvider.Mode = CipherMode.CBC
laesProvider.IV = _IV
laesProvider.Padding = PaddingMode.PKCS7
Dim ldecryptor As ICryptoTransform = laesProvider.CreateDecryptor
' Provide a memory stream to decrypt information into
Dim decryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(decryptedStream, ldecryptor, CryptoStreamMode.Write)
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock() '#### This is where the exception is thrown ####
decryptedStream.Position = 0
' Read the memory stream and convert it back into a string
Dim result(decryptedStream.Length - 1) As Byte
decryptedStream.Read(result, 0, decryptedStream.Length)
cryptStream.Close()
Return Encoding.Unicode.GetString(result)
End Function
The error occurs when attempting to decrypt certain length strings. When the string is a social security # (11 chars including dashes) then is throws "The input data is not a complete block" CryptographicException. If I pass in for example a string that is exactly 8 characters long, then everything works as expected. I thought that the PKCS7 padding would take care of the various lengths. I'm sure that I'm missing something simple, but after hours of googling, the answer eludes me.
The issue wasn't in the encryption method, it was in the length of the varbinary set in the database where it was being stored. So the encrypted data was being truncated.

Advice regarding encryption

I have a class called tdes which looks like this:
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Security.Cryptography
Imports System.IO
Namespace security
Public Class tdes
Private des As New TripleDESCryptoServiceProvider()
Private utf8 As New UTF8Encoding()
Private keyValue As Byte()
Private iVValue As Byte()
Public Property Key() As Byte()
Get
Return keyValue
End Get
Set(ByVal value As Byte())
keyValue = value
End Set
End Property
Public Property iV() As Byte()
Get
Return iVValue
End Get
Set(ByVal value As Byte())
iVValue = value
End Set
End Property
Public Sub New(ByVal key As Byte(), ByVal iV As Byte())
Me.keyValue = key
Me.iVValue = iV
End Sub
Public Function ByteDecrypt(ByVal bytes As Byte()) As String
Dim output As Byte()
output = Transform(bytes, des.CreateDecryptor(Me.keyValue, Me.iVValue))
'Return Convert.ToBase64String(output)
Return utf8.GetString(output)
End Function
Public Function ByteEncrypt(ByVal bytes As Byte()) As Byte()
Return Transform(bytes, des.CreateEncryptor(Me.keyValue, Me.iVValue))
End Function
Public Function StringDecrypt(ByVal text As String) As String
Dim input As Byte() = Convert.FromBase64String(text)
Dim output As Byte() = Transform(input, des.CreateDecryptor(Me.keyValue, Me.iVValue))
Return utf8.GetString(output)
End Function
Public Function StringEncrypt(ByVal text As String) As String
Dim input As Byte() = utf8.GetBytes(text)
Dim output As Byte() = Transform(input, des.CreateEncryptor(Me.keyValue, Me.iVValue))
Return Convert.ToBase64String(output)
End Function
Public Function StringEncryptByte(ByVal text As String) As Byte()
Dim input As Byte() = utf8.GetBytes(text)
Dim output As Byte() = Transform(input, des.CreateEncryptor(Me.keyValue, Me.iVValue))
'Return Convert.ToBase64String(output)
Return output
End Function
Private Function Transform(ByVal input As Byte(), ByVal cryptoTransform As ICryptoTransform) As Byte()
' Create the necessary streams
Dim memory As New MemoryStream()
Dim stream As New CryptoStream(memory, cryptoTransform, CryptoStreamMode.Write)
' Transform the bytes as requesed
stream.Write(input, 0, input.Length)
stream.FlushFinalBlock()
' Read the memory stream and convert it back into byte array
memory.Position = 0
Dim result As Byte() = New Byte(memory.Length - 1) {}
memory.Read(result, 0, result.Length)
' Clean up
memory.Close()
stream.Close()
' Return result
Return result
End Function
End Class
End Namespace
And it works well encrypting and decrypting things. I want to encrypt some existing passwords in a database table, so I've run a little script on them which encrypt them like so (lots missing for brevity):
Dim key As Byte() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Dim iv As Byte() = {8, 7, 6, 5, 4, 3, 2, 1}
Dim enc As New security.tdes(key, iv)
Dim i As Integer = 0
Using oConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("pitstopConnectionString").ConnectionString)
Using cmd As New SqlCommand("doUpdatePasswords", oConn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#userid", userid)
cmd.Parameters.AddWithValue("#newpassword", enc.StringEncryptByte(currentPassword))
oConn.Open()
Try
i = cmd.ExecuteNonQuery()
Catch ex As Exception
Exit Sub
End Try
End Using
End Using
This has successfully encrypted all my passwords for all the records in the table. Now, when I allow someone to login, I want to compare the two values (what was typed in, to what the stored password is) and I assumed the best way would be to decrypt the stored and compare using strings? Like so:
If (enc.ByteDecrypt(pwdenc).ToString() = pitstop.doMakeSafeForSQL(txtPassword.Text.ToString.ToLower)) Then
However, I get all sorts of bizarre errors; Unable to cast object of type 'System.String' to type 'System.Byte[]'. is one, Invalid character in a Base-64 string. is another based on how I call the password in the proceeding SQLDataReader:
Using oConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("pitstopConnectionString").ConnectionString)
Using cmd As New SqlCommand("doGetEncryptedForLogin", oConn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#email", pitstop.doMakeSafeForSQL(txtEmail.Text.ToString.ToLower))
oConn.Open()
Using dr As SqlDataReader = cmd.ExecuteReader()
If dr.HasRows() = True Then
While dr.Read()
pwdenc = dr("password_b")
End While
Else
pitstop.doLogIt("Denied login for [" & txtEmail.Text & "]")
litError.Text = "The details you have provided are incorrect. Please try again."
pnlDenied.Visible = True
Exit Sub
End If
dr.Close()
End Using
End Using
End Using
Help or advice welcomed, as I'm stumped here...
Since noone else seems to answer, I'll give you my own two cents. I remember having experienced a similiar situation when I started "playing" with encryption, more than three years ago; in my case the problem was somehow related with the Base64 conversion, though I cannot remember the exact details now.
I suggest you going through a calm and patient debugging session, tracking down all the values of the strings, the byte arrays before and after crypting and decrypting.
I understand it's not a great help, but I hope at least can direct you in the right direction.
I fixed this error by replacing my 'encryption' class with Jeff Atwood's (www.codinghorror.com) fantastic encryption tools.
I did want to salt the passwords and store the salt, but I run out of time to implement that and will have to return to it. In the meantime, I've used this code as my encrypt and decrypt functions - I hope this is of some assistance to someone:
Dim key As String = System.Configuration.ConfigurationManager.AppSettings("key").ToString()
Dim salty As String = pitstop.doMakeSafeForSQL(txtEmail.Text.ToString().ToLower())
Dim p As Encryption.Symmetric.Provider = Encryption.Symmetric.Provider.TripleDES
Dim sym As New Encryption.Symmetric(p)
sym.Key.Text = key
Dim encryptedData As Encryption.Data
encryptedData = sym.Encrypt(New Encryption.Data(pitstop.doMakeSafeForSQL(txtPassword.Text.ToString().ToLower())))
Decryption:
Dim decryptedData As Encryption.Data
Dim pr As Encryption.Symmetric.Provider = Encryption.Symmetric.Provider.TripleDES
Dim sym2 As New Encryption.Symmetric(pr)
sym2.Key.Text = System.Configuration.ConfigurationManager.AppSettings("key").ToString()
Try
decryptedData = sym2.Decrypt(encryptedData)
Catch ex As Exception
// removed for brevity //
End Try
If anyone has any articles or advice on how to create, store and retrieve salted passwords, I'd love to see it.
Chris

Resources