Padding Is invalid - rijndael encryption method - vb.net

I've been trying to encrypt the connection string so I don't write it anywhere.
Using ChatGPT I came across the Rijndael method.
Module:
Imports System.Security.Cryptography
Imports System.Text
Module DB
' Encrypt the connection string
Public Function EncryptConnectionString(connectionString As String, key As Byte(), iv As Byte()) As String
' Create a new Rijndael instance
Dim rijndael As New RijndaelManaged()
rijndael.Padding = PaddingMode.PKCS7
rijndael.Key = key
rijndael.IV = iv
' Convert the connection string to a byte array
Dim data As Byte() = Encoding.UTF8.GetBytes(connectionString)
' Encrypt the data using the Rijndael instance
Dim encryptedData As Byte() = rijndael.CreateEncryptor().TransformFinalBlock(data, 0, data.Length)
' Concatenate the key, the initialization vector, and the encrypted data
Dim encryptedConnectionString As Byte() = New Byte(rijndael.Key.Length + rijndael.IV.Length + encryptedData.Length - 1) {}
Array.Copy(rijndael.Key, encryptedConnectionString, rijndael.Key.Length)
Array.Copy(rijndael.IV, 0, encryptedConnectionString, rijndael.Key.Length, rijndael.IV.Length)
Array.Copy(encryptedData, 0, encryptedConnectionString, rijndael.Key.Length + rijndael.IV.Length, encryptedData.Length)
' Convert the encrypted connection string to a base64 string
Return Convert.ToBase64String(encryptedConnectionString)
End Function
' Decrypt the connection string
Public Function DecryptConnectionString(encryptedConnectionString As String, key As Byte(), iv As Byte()) As String
' Convert the encrypted connection string from a base64 string
Dim encryptedConnectionBytes As Byte() = Convert.FromBase64String(encryptedConnectionString)
' Extract the key and initialization vector from the encrypted connection string
Dim decryptedKey As Byte() = New Byte(key.Length - 1) {}
Dim decryptedIV As Byte() = New Byte(iv.Length - 1) {}
Array.Copy(encryptedConnectionBytes, decryptedKey, key.Length)
Array.Copy(encryptedConnectionBytes, key.Length, decryptedIV, 0, iv.Length)
'Create a New Rijndael instance
Dim rijndael As New RijndaelManaged()
rijndael.Padding = PaddingMode.PKCS7
rijndael.Key = decryptedKey
rijndael.IV = decryptedIV
' Extract the encrypted data from the encrypted connection string
Dim encryptedData As Byte() = New Byte(encryptedConnectionBytes.Length - key.Length - iv.Length - 1) {}
Array.Copy(encryptedConnectionBytes, key.Length + iv.Length, encryptedData, 0, encryptedData.Length)
' Decrypt the data using the Rijndael instance
Dim decryptedData As Byte() = rijndael.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length)
' Convert the decrypted data to a string and return it
Return Encoding.UTF8.GetString(decryptedData)
End Function
End Module`
Form to test:
Imports System.Security.Cryptography
Imports System.Text
Public Class Form1
Private Sub BtnEncrypt_Click(sender As Object, e As EventArgs) Handles btnEncrypt.Click
' Generate a new key and initialization vector
Dim key As Byte() = New Byte(31) {}
Dim iv As Byte() = New Byte(15) {}
Using rng As New RNGCryptoServiceProvider()
rng.GetBytes(key)
rng.GetBytes(iv)
End Using
' Encrypt the connection string
Dim connectionString As String = "Server=" & txtIP.Text & ";Database=" & txtDatabase.Text & ";User ID=" & txtUsername.Text & ";Password=" & txtPassword.Text & ";port=" & txtPort.Text & ";"
Dim rijndael As New RijndaelManaged()
rijndael.Padding = PaddingMode.PKCS7
rijndael.Key = key
rijndael.IV = iv
Dim data As Byte() = Encoding.UTF8.GetBytes(connectionString)
Dim encryptedData As Byte() = rijndael.CreateEncryptor().TransformFinalBlock(data, 0, data.Length)
Dim encryptedConnectionString As String = Convert.ToBase64String(encryptedData)
'Save the encrypted connection string And the key And IV to the settings
My.Settings.EncryptedConnectionString = encryptedConnectionString
My.Settings.Key = Convert.ToBase64String(key)
My.Settings.IV = Convert.ToBase64String(iv)
My.Settings.Save()
txtconnectionstring.Text = encryptedConnectionString
txtKey.Text = Convert.ToBase64String(key)
txtIV.Text = Convert.ToBase64String(iv)
End Sub
Private Sub btnDecrypt_Click(sender As Object, e As EventArgs) Handles btnDecrypt.Click
' Retrieve the encrypted connection string, key, and IV from your settings or configuration
Dim encryptedConnectionString As String = My.Settings.EncryptedConnectionString
Dim key As Byte() = Convert.FromBase64String(txtKey.Text)
Dim iv As Byte() = Convert.FromBase64String(txtIV.Text)
' Decrypt the connection string using the key and IV
Dim connectionString As String = DecryptConnectionString(encryptedConnectionString, key, iv)
txtconnectionstring.Clear()
txtconnectionstring.Text = connectionString
End Sub
End Class
So Encryption is working good but decrypt is giving me hell. Error is: Padding is invalid and cannot be removed.
System.Security.Cryptography.CryptographicException
HResult=0x80131430
Message=Padding is invalid and cannot be removed.
Source=mscorlib
StackTrace:
at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
For a little bit more context because i've read that the IV or KEY neeed to be the same. I saved those keys manual on the settings or i've saved it on the text box. I've always got the same error while decrypting.
If anyone could help,
Fábio
Tried to encrypt my connection string and save it to the settings of the app. Now I was trying to decrypt it so it could be used to connection to the mysql server.

Related

VB NET AES encrypt

Can't reproduce an AES online encoder example using VB.Net
Trying in https://www.devglan.com/online-tools/aes-encryption-decryption with following parameters:
Text to be Encrypted: test
Cipher Mode: ECB
Key Size: 128
Secret Key: 1234567890123456
I get this output: 3fvaLg5IDlveswuXzhVQcw==
If I try in VB.Net using this function (found in https://gist.github.com/ShaneGowland/5973974):
Public Shared Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
Return ex.ToString
End Try
End Function
I get this output: 6mhZOr1dQ7PWqbRGzmMgjg== which is not matching with got at devglan.com
I tried with different paddings with no luck. What am I doing wrong?
PS: I am aware that the ECB method should not be used
Working with this function:
Public Shared Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
AES.Mode = CipherMode.ECB
AES.Key = Encoding.UTF8.GetBytes(pass)
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
Return ex.ToString
End Try
End Function

Problems with encryption and decryption TripleDES in vb.net

I'm practicing encryption and decryption with a text file by using TipleDES. I enter a word in a text box, which is in my application, and then click my button that will store the password in the text file. I check the text file to see if it encrypts it which it does and then I try to decrypt the text. It encrypts it again and doesn't decrypt it. I'm not sure what I'm doing wrong.
Public Function EncryptTripleDES(strInput As String, btKey As String) As String
Dim desTDES As New TripleDESCryptoServiceProvider()
Dim hashMD5TDES As New MD5CryptoServiceProvider()
Dim btHash As Byte()
Dim btBuff As Byte()
btHash = hashMD5TDES.ComputeHash(Encoding.UTF8.GetBytes(btKey))
desTDES.Key = btHash
desTDES.Mode = CipherMode.ECB
btBuff = Encoding.UTF8.GetBytes(strInput)
Dim strResult As String = Convert.ToBase64String _
(desTDES.CreateEncryptor().TransformFinalBlock(btBuff, 0,
btBuff.Length))
Return strResult
End Function
Public Function DecryptTripleDES(strInput As String, btKey As String) As String
Dim desTDES As New TripleDESCryptoServiceProvider()
Dim hashMD5TDES As New MD5CryptoServiceProvider()
Dim btHash As Byte()
Dim btBuff As Byte()
btHash = hashMD5TDES.ComputeHash(Encoding.UTF8.GetBytes(btKey))
desTDES.Key = btHash
desTDES.Mode = CipherMode.ECB
btBuff = Convert.FromBase64String(strInput)
Dim strResult As String = Encoding.UTF8.GetString _
(desTDES.CreateDecryptor().TransformFinalBlock(btBuff, 0,
btBuff.Length))
Return strResult
End Function
These are my functions to encrypt and decrypt.
strEncode = EncryptTripleDES(EmailPasswordTextBox.Text, "HTG")
strDecode = DecryptTripleDES(strEncode, "HTG")
Console.WriteLine("Encrypted: {0}", strEncode)
Console.WriteLine("Decrypted: {0}", strDecode)
If I change EmailPasswordTextBox.Text to "This is a Test". It works perfectly. What am I doing wrong?

Sage Pay error 3045 : The Currency field is missing. MALFORMED

I am trying to upgrade sage pay version from 2.22 to 3.00 and I am using Form Intergration to submit the values to Sage. The codes written asp.net(VB). In 2.2, it was using "SimpleXor encryption algorithm", but that doesn't allowed in version 3.00 and as a result, I am getting the below error message:
This transaction attempt has failed. We are unable to redirect you back to the web store from which you were purchasing. The details of the failure are given below.
Status: INVALID
Status Detail: 5068 : The encryption method is not supported by this protocol version.
I found, version 3.00 allowed only AES encryption, And I have added the below code in class file for encryption:
Public Shared Function AESEncrypt(ByVal clearText As String) As String
Dim EncryptionKey As String = "MAKV2SPBNI99212"
Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText)
Using encryptor As Aes = Aes.Create()
Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
&H65, &H64, &H76, &H65, &H64, &H65, _
&H76})
encryptor.Key = pdb.GetBytes(32)
encryptor.IV = pdb.GetBytes(16)
Using ms As New MemoryStream()
Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
cs.Write(clearBytes, 0, clearBytes.Length)
cs.Close()
End Using
clearText = Convert.ToBase64String(ms.ToArray())
End Using
End Using
Return clearText
End Function
And in main .vb file, I change below code:
Dim strXOR As String = simpleXor(strPost, strEncryptionPassword)
strCrypt = base64Encode(strXOR)
To
Dim aesEncrypt As String = AESEncrypt(strPost)
strCrypt = "#" & aesEncrypt
Sorry, I am begginer on this. Is there any mistakes I did in my class file Or in main vb file? Do I need to base64encode after aes encryption?
Thank you in advance.
OK. Compete answer rewrite.
Ditch the code you have - I found it on another site and it isn't going to work.
Instead, use the stuff below (which I've adapted very slightly from here) :
Public Shared Function AESEncryption(ByVal strCrypt As String, ByVal strEncryptionPassword As String) As String
Dim keyAndIvBytes As Byte() = UTF8Encoding.UTF8.GetBytes(strEncryptionPassword)
Using AES As New RijndaelManaged()
' Set the mode, padding and block size for the key
AES.Padding = PaddingMode.PKCS7
AES.Mode = CipherMode.CBC
AES.KeySize = 128
AES.BlockSize = 128
' Encrypt the string to an array of bytes.
Dim encrypted As Byte() = EncryptStringToBytes(strCrypt, keyAndIvBytes, keyAndIvBytes)
AESEncryption = "#" & BitConverter.ToString(encrypted).Replace("-", "").ToUpper
' System.Console.WriteLine(AESEncryption)
End Using
End Function
Public Shared Function AESDecryption(ByVal strCrypt As String, ByVal strEncryptionPassword As String) As String
Dim keyAndIvBytes As [Byte]() = UTF8Encoding.UTF8.GetBytes(strEncryptionPassword)
' Create a new instance of the RijndaelManaged
' class. This generates a new key and initialization
' vector (IV).
Using AES As New RijndaelManaged()
' Set the mode, padding and block size for the key
AES.Padding = PaddingMode.PKCS7
AES.Mode = CipherMode.CBC
AES.KeySize = 128
AES.BlockSize = 128
Dim encryptedData As Byte() = StringToByteArray(strCrypt.Remove(0, 1))
Dim roundtrip As String = DecryptStringFromBytes(encryptedData, keyAndIvBytes, keyAndIvBytes)
AESDecryption = roundtrip
End Using
End Function
Shared Function byteArrayToHexString(ByVal ba As Byte()) As String
Return BitConverter.ToString(ba).Replace("-", "")
End Function
Shared Function StringToByteArray(ByVal hex As String) As Byte()
Return Enumerable.Range(0, hex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(hex.Substring(x, 2), 16)).ToArray()
End Function
Shared Function EncryptStringToBytes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
' Check arguments.
If plainText Is Nothing OrElse plainText.Length <= 0 Then
Throw New ArgumentNullException("plainText")
End If
If Key Is Nothing OrElse Key.Length <= 0 Then
Throw New ArgumentNullException("Key")
End If
If IV Is Nothing OrElse IV.Length <= 0 Then
Throw New ArgumentNullException("IV")
End If
Dim encrypted() As Byte
' Create an RijndaelManaged object
' with the specified key and IV.
Using AES As New RijndaelManaged()
AES.Padding = PaddingMode.PKCS7
AES.Mode = CipherMode.CBC
AES.KeySize = 128
AES.BlockSize = 128
AES.Key = Key
AES.IV = IV
' Create a decrytor to perform the stream transform.
Dim encryptor As ICryptoTransform = AES.CreateEncryptor(AES.Key, AES.IV)
' Create the streams used for encryption.
Using msEncrypt As New MemoryStream()
Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
Using swEncrypt As New StreamWriter(csEncrypt)
'Write all data to the stream.
swEncrypt.Write(plainText)
End Using
encrypted = msEncrypt.ToArray()
End Using
End Using
End Using
' Return the encrypted bytes from the memory stream.
Return encrypted
End Function 'EncryptStringToBytes
Shared Function DecryptStringFromBytes(ByVal cipherText() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
' Check arguments.
If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
Throw New ArgumentNullException("cipherText")
End If
If Key Is Nothing OrElse Key.Length <= 0 Then
Throw New ArgumentNullException("Key")
End If
If IV Is Nothing OrElse IV.Length <= 0 Then
Throw New ArgumentNullException("IV")
End If
' Declare the string used to hold
' the decrypted text.
Dim plaintext As String = Nothing
' Create an RijndaelManaged object
' with the specified key and IV.
Using AES As New RijndaelManaged
AES.Padding = PaddingMode.PKCS7
AES.Mode = CipherMode.CBC
AES.KeySize = 128
AES.BlockSize = 128
'AES.Key = Key
'AES.IV = IV
' Create a decrytor to perform the stream transform.
Dim decryptor As ICryptoTransform = AES.CreateDecryptor(Key, IV)
' Create the streams used for decryption.
Using msDecrypt As New MemoryStream(cipherText)
Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
Using srDecrypt As New StreamReader(csDecrypt)
' Read the decrypted bytes from the decrypting stream
' and place them in a string.
plaintext = srDecrypt.ReadToEnd()
End Using
End Using
End Using
End Using
Return plaintext
End Function
And in your main.vb file change:
Dim strXOR As String = simpleXor(strPost, strEncryptionPassword)
strCrypt = base64Encode(strXOR)
To:
strCrypt=AESEncryption(strPost, strEncryptionPassword)

vb.net rijndael limit to 64 character

i have problem while encrypt and decrypt using rijndael in vb.net.
it cannot work on string more than 64 character.
here is my code:
Private Function prepareRijn() As Rijndael
Dim KEY As String = Left(_KEY, 32)
Dim IV As String = Right(_KEY, 32)
Dim enc As New System.Text.UTF8Encoding
Dim byteKEY() As Byte = enc.GetBytes(KEY)
Dim byteIV() As Byte = enc.GetBytes(IV)
Dim alg As Rijndael = Rijndael.Create
alg.BlockSize = 256
alg.KeySize = 256
alg.Padding = PaddingMode.Zeros
alg.Mode = CipherMode.CBC
alg.Key = byteKEY
alg.IV = byteIV
Return alg
End Function
Function decrypt(ByVal encrypted As String) As String
encrypted = encrypted.Replace("Q2FrZQ==.", "")
Dim enc As New System.Text.UTF8Encoding
Dim alg As Rijndael = prepareRijn()
Dim ms As New MemoryStream
Dim cs As CryptoStream = New CryptoStream(ms, alg.CreateDecryptor, CryptoStreamMode.Write)
Dim data() As Byte = Convert.FromBase64String(encrypted)
cs.Write(data, 0, data.Length)
'ms.SetLength(data.Length)
Dim decrypted() As Byte
decrypted = ms.ToArray
cs.Close()
Return enc.GetString(decrypted)
End Function
Function encrypt(ByVal decrypt As String) As String
decrypt = decrypt + " "
Dim alg As Rijndael = prepareRijn()
Dim ms As New MemoryStream()
Dim cs As CryptoStream = New CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write)
Dim data() As Byte = System.Text.Encoding.UTF8.GetBytes(decrypt)
cs.Write(data, 0, data.Length)
'ms.SetLength(data.Length)
Dim encrypted() As Byte = ms.ToArray()
cs.Close()
Return Convert.ToBase64String(encrypted)
End Function
is there anything i miss during my rijndael configuration ?
I wrote complete Encryption Class for you. It works perfectly. It can be used for Both Strings and ByteArrays. This Class returns Encrypted Data in Base64, if you dont want Base64, just remove Conversion.
Imports System.Text
Imports System.Security.Cryptography
Imports System.IO
Imports System
Public Class Encryption
' Fields
Private Shared sIV As String = "Your IV Key Placed Here 32-Bytes"
Private Shared sKey As String = "Your SecKey Placed Here 32-Bytes"
' Methods
Public Shared Function DecryptRJ256(ByVal prm_text_to_decrypt As String) As String
Dim s As String = prm_text_to_decrypt
Dim managed As New RijndaelManaged With { _
.Padding = PaddingMode.Zeros, _
.Mode = CipherMode.ECB, _
.KeySize = &H100, _
.BlockSize = &H100 _
}
Dim rgbKey As Byte() = Nothing
Dim rgbIV As Byte() = Nothing
s = s.Replace("-", "+").Replace("_", "/").Replace("|", "=")
rgbKey = Encoding.ASCII.GetBytes(Encryption.sKey)
rgbIV = Encoding.ASCII.GetBytes(Encryption.sIV)
Dim transform As ICryptoTransform = managed.CreateDecryptor(rgbKey, rgbIV)
Dim buffer As Byte() = Convert.FromBase64String(s)
Dim buffer4 As Byte() = New Byte((buffer.Length + 1) - 1) {}
Dim stream As New MemoryStream(buffer)
Dim stream2 As New CryptoStream(stream, transform, CryptoStreamMode.Read)
stream2.Read(buffer4, 0, buffer4.Length)
Return Encoding.ASCII.GetString(buffer4)
End Function
Public Shared Function EncryptRJ256(ByVal prm_text_to_encrypt As String) As String
Dim s As String = prm_text_to_encrypt
Dim managed As New RijndaelManaged With { _
.Padding = PaddingMode.Zeros, _
.Mode = CipherMode.ECB, _
.KeySize = &H100, _
.BlockSize = &H100 _
}
Dim buffer As Byte() = Nothing
Dim rgbKey As Byte() = Nothing
Dim rgbIV As Byte() = Nothing
rgbKey = Encoding.ASCII.GetBytes(Encryption.sKey)
rgbIV = Encoding.ASCII.GetBytes(Encryption.sIV)
Dim transform As ICryptoTransform = managed.CreateEncryptor(rgbKey, rgbIV)
Dim stream As New MemoryStream
Dim stream2 As New CryptoStream(stream, transform, CryptoStreamMode.Write)
buffer = Encoding.ASCII.GetBytes(s)
stream2.Write(buffer, 0, buffer.Length)
stream2.FlushFinalBlock()
Return Convert.ToBase64String(stream.ToArray).Replace("+", "-").Replace("/", "_").Replace("=", "|")
End Function
Public Shared Function EncryptRJ256(ByVal ArrayByte As Byte()) As String
Dim managed As New RijndaelManaged With { _
.Padding = PaddingMode.Zeros, _
.Mode = CipherMode.ECB, _
.KeySize = &H100, _
.BlockSize = &H100 _
}
Dim rgbKey As Byte() = Nothing
Dim rgbIV As Byte() = Nothing
rgbKey = Encoding.ASCII.GetBytes(Encryption.sKey)
rgbIV = Encoding.ASCII.GetBytes(Encryption.sIV)
Dim transform As ICryptoTransform = managed.CreateEncryptor(rgbKey, rgbIV)
Dim stream As New MemoryStream
Dim stream2 As New CryptoStream(stream, transform, CryptoStreamMode.Write)
stream2.Write(ArrayByte, 0, ArrayByte.Length)
stream2.FlushFinalBlock()
Return Convert.ToBase64String(stream.ToArray).Replace("+", "-").Replace("/", "_").Replace("=", "|")
End Function
Public Shared Function getMD5Hash(ByVal input As String) As String
Dim md As MD5 = MD5.Create
Dim bytes As Byte() = Encoding.ASCII.GetBytes(input)
Dim buffer2 As Byte() = md.ComputeHash(bytes)
Dim builder As New StringBuilder
Dim i As Integer
For i = 0 To buffer2.Length - 1
builder.Append(buffer2(i).ToString("X2"))
Next i
Return builder.ToString
End Function
Public Shared Function FromBase64String(ByVal prm_text_to_decrypt As String) As String
Dim s As String = prm_text_to_decrypt
s = s.Replace("-", "+").Replace("_", "/").Replace("|", "=")
Dim buffer As Byte() = Convert.FromBase64String(s)
Return Encoding.ASCII.GetString(buffer)
End Function
End Class

Serialization Cryptography Error

I am having trouble using encryption with serialization when deserializing an object.
This is the error:
Failed to deserialize. Reason: End of Stream encountered before parsing was completed
Here is my code:
Imports System.IO
Imports System.Security.Cryptography
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Text
Module TestModEncryption
Public Sub SaveEncryptedObjectToFile(FileName As String, Item As Object)
Dim fs As FileStream
Dim encryptor As CryptoStream
Dim formatter As New BinaryFormatter
Dim password As String = "MyPassword"
Dim salt As String = "InitialVector123"
Dim AES As AesManaged = New AesManaged
AES.Padding = PaddingMode.None
AES.Mode = CipherMode.CBC
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
Dim PasswordIterations As Integer = 2
Dim InitialVector As String = "InitialVector123" 'This should be a string of 16 ASCII characters.
Dim KeySize As Integer = 256 'Can be 128, 192, or 256.
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As New Rfc2898DeriveBytes(password, SaltValueBytes, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(CInt(KeySize / 8))
Dim encryptTransf As ICryptoTransform = AES.CreateEncryptor(KeyBytes, InitialVectorBytes)
fs = New FileStream(FileName, FileMode.Create)
encryptor = New CryptoStream(fs, encryptTransf, CryptoStreamMode.Write)
Try
formatter.Serialize(encryptor, Item)
Catch e As SerializationException
Console.WriteLine("Failed to serialize. Reason: " & e.Message)
Throw
Finally
fs.Close()
End Try
End Sub
Public Function OpenEncryptedObjectFromFile(FileName As String) As Object
Dim fs As New FileStream(FileName, FileMode.Open)
Dim decryptor As CryptoStream
Dim ItemToReturn As New Object
Dim password As String = "MyPassword"
Dim salt As String = "InitialVector123"
Dim AES As AesManaged = New AesManaged
AES.Padding = PaddingMode.None
AES.Mode = CipherMode.CBC
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
Dim PasswordIterations As Integer = 2
Dim InitialVector As String = "InitialVector123" 'This should be a string of 16 ASCII characters.
Dim KeySize As Integer = 256 'Can be 128, 192, or 256.
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As New Rfc2898DeriveBytes(password, SaltValueBytes, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(CInt(KeySize / 8))
Dim decryptTrans As ICryptoTransform = AES.CreateDecryptor(KeyBytes, InitialVectorBytes)
Try
Dim formatter As New BinaryFormatter
decryptor = New CryptoStream(fs, decryptTrans, CryptoStreamMode.Read)
ItemToReturn = DirectCast(formatter.Deserialize(decryptor), Object)
Return ItemToReturn
Catch e As SerializationException
MsgBox("Failed to deserialize. Reason: " & e.Message)
Return Nothing
'Throw
Finally
fs.Close()
End Try
End Function
End Module
Crypto is somewhat complex. First get the crypto working, just the crypto. Start with a piece of text: "I wandered lonely as an armadillo." Use your code to encrypt and decrypt that text, forgetting about the serialization. When that is working correctly then, and only then, use your working crypto code to encrypt/decrypt the serialized object.
Have you successfully serialized/deserialized your object without any encryption?
On a brief glance, you need to set padding to PKCS#7 (aka PKCS#5). Your PaddingMode.None may be what is causing the problem. Without padding your final block may not be being processed correctly. Obviously you need to use the same padding for both encryption and decryption.