OutOfMemoryException while using CryptoStream with large Strings in VB.NET - vb.net

my program runs into a OutOfMemoryException when I use large Strings with the following method.
Public Function EncryptData(ByVal plaintext As String) As String
Dim plaintextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext)
Dim ms As New System.IO.MemoryStream
Dim encStream As New CryptoStream(ms, TripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
encStream.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray)
End Function
The following Line is causing the exception:
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
How can I fix this problem? My method works fine with short strings.

Related

VB.net Delete a File after Creating Byte

When I try to delete a Tiff file after creating a byte I get an error stating that I cannot access file because it is being accessed by another process. I am Printing the Byte after the fact if that matters.
Dim image As System.Drawing.Image = System.Drawing.Image.FromFile(strFile)
Dim imageConverter As New ImageConverter()
Dim Bytes As Byte() = DirectCast(imageConverter.ConvertTo(image, GetType(Byte())), Byte())
Dim PageSettings As New PageSettings
Dim FS As New FileStream("C:\clean\Packing\output.TIF", FileMode.Create)
FS.Write(Bytes, 0, Bytes.Length)
FS.Close()
FS.Dispose()
IO.File.Delete(strFile)
Try to implement the Using Statement to dispose the object after you finish using it.
The End Using statement disposes of the resources under the Using block's control.
Using image = System.Drawing.Image.FromFile(strFile)
Dim imageConverter As New ImageConverter()
Dim Bytes As Byte() = DirectCast(imageConverter.ConvertTo(image, GetType(Byte())), Byte())
Dim pageSettings = New PageSettings
Using FS = New FileStream("C:\clean\Packing\output.TIF", FileMode.Create)
FS.Write(Bytes, 0, Bytes.Length)
End Using
End Using
IO.File.Delete(strFile)

Encrypt/Decrypt data in Vb.net and SQL Server

I currently use two functions, in a VB.net application, to encrypt/decrypt sensitive data (e.g. SSNs). I then store the encrypted data in a SQL Server database. Then, when reading data from SQL Server, the application decrypts it for display. This works just fine.
The problem with this solution is that it makes it impossible to write simple SQL queries that include those encrypted fields as the data that comes back is encrypted. I want to be able to run queries that return the data that was stored in encrypted format, in its original format (i.e. the actual, unencrypted data).
What is the best practice for accomplishing this? Should I not be using functions in the VB.net application, but rather using functions in SQL Server, for example? Or, do I need to create a DLL or something that has the two aforementioned functions that I then need to "install" somehow, so that they can be called from SQL Server? I am using SQL Server 2008 and Visual Studio 2017.
In case it's relevant, I have included the code for the functions.
Private key() As Byte = {}
Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Public Function Decrypt(ByVal sStringToDecrypt As String, _
ByVal sEncryptionKey As String) As String
Dim inputByteArray(sStringToDecrypt.Length) As Byte
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))
Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(sStringToDecrypt)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), _
CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function Encrypt(ByVal sStringToEncrypt As String, _
ByVal SEncryptionKey As String) As String
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))
Dim des As New DESCryptoServiceProvider()
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes( _
sStringToEncrypt)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), _
CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function

System.Security.Cryptography.CryptographicException: Bad Data

I am having this bad data problem when I tried to open it. Any idea how to solve it? When I debug it shows that CryptoStream.FlushFinalBlock() is having a problem. See codes below.
Public Class Encryption
Public Function Encrypt(ByVal plainText As String) As Byte()
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, 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
Public Function Decrypt(ByVal inputInBytes() As Byte) As String
' UTFEncoding is used to transform the decrypted Byte Array
' information back into a string.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' As before we must provide the encryption/decryption key along with
' the init vector.
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateDecryptor(Me.key, Me.iv)
' Provide a memory stream to decrypt information into
Dim decryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = 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 into a string
Dim result(decryptedStream.Length - 1) As Byte
decryptedStream.Read(result, 0, decryptedStream.Length)
cryptStream.Close()
Dim myutf As UTF8Encoding = New UTF8Encoding()
Return myutf.GetString(result)
End Function
End Class
After the cryptStream.Write you can close it and return the MemoryStream data
Public Function Encrypt(ByVal plainText As String) As Byte()
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.Close()
encryptedStream.Position = 0
Return encryptedStream.ToArray()
End Function
Update: Decrypt Method
Public Function Decrypt(ByVal inputInBytes() As Byte) As String
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' As before we must provide the encryption/decryption key along with
' the init vector.
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateDecryptor(Me.key, Me.iv)
' Provide a memory stream to decrypt information into
Dim decryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(decryptedStream, cryptoTransform, CryptoStreamMode.Write)
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
Return System.Text.Encoding.Unicode.GetString(decryptedStream.ToArray)
End Function
Public Function Decrypt(ByVal inputInBytes() As Byte) As String
' UTFEncoding is used to transform the decrypted Byte Array
' information back into a string.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' As before we must provide the encryption/decryption key along with
' the init vector.
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateDecryptor(Me.key, Me.iv)
' Provide a memory stream to decrypt information into
Dim decryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = 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 into a string
Dim result(decryptedStream.Length - 1) As Byte
decryptedStream.Read(result, 0, decryptedStream.Length)
cryptStream.Close()
Dim myutf As UTF8Encoding = New UTF8Encoding()
Return myutf.GetString(result)
End Function
End Class

Encryption of email address in vb.net

I would like to know how I can encrypt an email address via vb.net code.
I found one sample which doesn't quite work with special characters and I am getting this error:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
Here is the code I am trying:
'The function used to encrypt the text
Private Function Encrypt(ByVal strText As String, ByVal strEncrKey _
As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Try
byKey = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
Dim des As New DESCryptoServiceProvider()
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strText)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
What do you guys think? What am I doing wrong?
Thanks, Laziale
UPDATE: Full Stack trace:
System.FormatException was caught
Message=The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
Source=mscorlib
StackTrace:
at System.Convert.FromBase64String(String s)
at WEbsite.Login.Decrypt(String strText, String sDecrKey) in D:\Website\Account\Login.aspx.vb:line 213
InnerException:
UPDATE 2:
Encryption method added:
'The function used to decrypt the text
Private Function Decrypt(ByVal strText As String, ByVal sDecrKey _
As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Dim inputByteArray(strText.Length) As Byte
Try
byKey = System.Text.Encoding.UTF8.GetBytes(Left(sDecrKey, 8))
Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(strText)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
I have tried your Decrypt using, as input, the encrypted text and the same key.
It works as expected. The only change I have made to your code is the use of the Substring method instead of Left as in
byKey = System.Text.Encoding.UTF8.GetBytes(strDecrKey.Substring(0, 8))
I call the two methods in this way:
Dim result as String = Encrypt("test#gmail.com", "ABCD9876")
Dim decrypted = Decrypt(result, "ABCD9876")
I get back "test#gmail.com".
-Buon Weekend anche a te-
Use an String Builder instead of string as the parameter with the special characters.
Best regards.

VB.Net DES encryption function, to Triple DES

Public Shared Function DESEncrypt(ByVal Data As String, ByVal Key As String) As Byte()
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Try
Dim bykey() As Byte = System.Text.Encoding.UTF8.GetBytes(Left(Key, 8))
Dim InputByteArray() As Byte = System.Text.Encoding.UTF8.GetBytes(Data)
Dim des As New DESCryptoServiceProvider
Dim ms As New MemoryStream
Dim cs As New CryptoStream(ms, des.CreateEncryptor(bykey, IV), CryptoStreamMode.Write)
cs.Write(InputByteArray, 0, InputByteArray.Length)
cs.FlushFinalBlock()
Return ms.ToArray()
Catch ex As Exception
End Try
End Function
this is what I currently have for my DES encryption, but as I am fairly new to VB.Net I can figure out how to make it use Triple DES rather than DES
Try this
Public Shared Function DESEncrypt(ByVal Data As String, ByVal Key As String) As Byte()
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Try
Dim bykey() As Byte = System.Text.Encoding.UTF8.GetBytes(Left(Key, 24))
If String.IsNullOrEmpty(Data) Then
Throw New ArgumentException("No data passed", "input")
ElseIf bykey Is Nothing OrElse bykey.Length <> 24 Then
Throw New ArgumentException("Invalid Key. Key must be 24 bytes length", "key")
End If
Dim InputByteArray() As Byte = System.Text.Encoding.UTF8.GetBytes(Data)
Using ms As New IO.MemoryStream
Using des As New Security.Cryptography.TripleDESCryptoServiceProvider
Using cs As New Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(bykey, IV), Security.Cryptography.CryptoStreamMode.Write)
cs.Write(InputByteArray, 0, InputByteArray.Length)
cs.FlushFinalBlock()
Return ms.ToArray()
End Using
End Using
End Using
Catch ex As Exception
End Try
End Function