Encryption keysize and algorithm - vb.net

Here is some code that I have that works perfectly:
Sub EncryptFile(ByVal sInputFilename As String, _
ByVal sOutputFilename As String, _
ByVal sKey As String)
Dim fsInput As New FileStream(sInputFilename, _
FileMode.Open, FileAccess.Read)
Dim fsEncrypted As New FileStream(sOutputFilename, _
FileMode.Create, FileAccess.Write)
Dim DES As New DESCryptoServiceProvider()
'Set secret key for DES algorithm.
'A 64-bit key and an IV are required for this provider.
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
'Set the initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
'Create the DES encryptor from this instance.
Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
'Create the crypto stream that transforms the file stream by using DES encryption.
Dim cryptostream As New CryptoStream(fsEncrypted, _
desencrypt, _
CryptoStreamMode.Write)
'Read the file text to the byte array.
Dim bytearrayinput(fsInput.Length - 1) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
'Write out the DES encrypted file.
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
End Sub
Is it possible to change the keysize and maybe even choose between MD5 and SHA1 encryption with this code? If not, can someone point me in the right direction to find some that does?
thanks
Simon

DES is an encryption algorithm. If you want to use something else you should look at the TripleDESCryptoServiceProvider, or the AesCryptoServiceProvider (in the System.Security.Cryptography namespace).
MD5 and SHA1 are actually hashing algorithms. Effectively they are special case one-way encryption algorithms that can not be decrypted (so I don't think they are what you are looking for).
Just looking at the documentation for TripleDES and Aes classes it looks like you should be able to replace the line:
Dim DES As New DESCryptoServiceProvider()
with any of the other CryptoServiceProvider classes that provides a CreateEncryptor function. They also support a KeySize property that you can set. You might try something like:
Sub EncryptFile(ByVal sInputFilename As String, _
ByVal sOutputFilename As String, _
ByVal sKey As String, _
ByVal keysize as integer, _
ByVal algorithm as String)
Dim fsInput As New FileStream(sInputFilename, _
FileMode.Open, FileAccess.Read)
Dim fsEncrypted As New FileStream(sOutputFilename, _
FileMode.Create, FileAccess.Write)
Dim algorithm As SymmetricAlgorithm
Select Case algorithm
Case "DES": algorithm = New DESCryptoServiceProvider()
Case "3DES": algorithm = New TripleDESCryptoServiceProvider()
Case "AES": algorithm = New AESCryptoServiceProvider()
End Select
algorithm.KeySize = keysize
'Set secret key for the algorithm.
'A 64-bit key and an IV are required for this provider.
algorithm.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
'Set the initialization vector.
algorithm.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
'Create the encryptor from this instance.
Dim desencrypt As ICryptoTransform = algorithm.CreateEncryptor()
'Create the crypto stream that transforms the file stream by using encryption.
Dim cryptostream As New CryptoStream(fsEncrypted, _
desencrypt, _
CryptoStreamMode.Write)
'Read the file text to the byte array.
Dim bytearrayinput(fsInput.Length - 1) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
'Write out the DES encrypted file.
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
End Sub
I haven't tried to compile the above sample but that you get you started I hope.

Related

vb.net: DES decryption error while using memory stream

This is my code for des decryption. I dont know why it showing error on CopyTo function.
Private Function Unsecure(ByVal sInput As Byte(), ByVal sKey As String)
'Define the service provider
Dim DES As New DESCryptoServiceProvider()
DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
'Define the crypto transformer
Dim cryptoTransform As ICryptoTransform
cryptoTransform = DES.CreateDecryptor
Dim ms As New MemoryStream(sInput)
Dim cryptostream As New CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read)
Dim ms1 As New MemoryStream()
cryptostream.CopyTo(ms1) '// <- **Error: CopyTo is not a member of System.Security.Cryptography.Cryptostream**
Return ms1.ToArray()
End Function

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)

Decrypt the contents of a folder - VB.NET

I've been tasked with making an encryption program and part of the task is to Encrypt/Decrypt a folder.
The encryption works exactly how I want but when I try to decrypt it gives me an error:
"Length of the data to decrypt is invalid".
All I can say I've really changed is that I'm using DES.CreateDecryptor instead of the DES.CreateEncryptor in my encryption code. Though it looks like there's more to it than that for it to work.
Just wondering how I fix this really. I'll leave the relevant portion of my code below.
Dim folderinfo As New DirectoryInfo(folderpath)
For Each File In Directory.GetFiles(folderinfo.FullName)
Dim outputFile As String
outputFile = File
Dim fsInput As New FileStream(File, FileMode.Open, FileAccess.Read)
Dim bytearrayinput(fsInput.Length) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
fsInput.Close()
Dim skey As String
skey = Encrypt
Dim fsDecrypted As New FileStream(File, FileMode.Create, FileAccess.Write)
Dim DES As New DESCryptoServiceProvider
DES.Key = ASCIIEncoding.ASCII.GetBytes(skey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(skey)
Dim desdecrypt As ICryptoTransform
desdecrypt = DES.CreateDecryptor()
Dim cryptostream As New CryptoStream(fsDecrypted, desdecrypt, CryptoStreamMode.Write)
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
fsDecrypted.Close()
txtDecrypt.Text = "All files decrypted"
You've done a classic mistake when instantiating the array. An array should be instantiated with the size (n - 1) where n is the number of elements. To set the right size, all you have to do is to subtract 1 from the fsInput length.
Dim bytearrayinput(fsInput.Length - 1) As Byte

The process cannot access the file[VB.Net]

I'm trying to save a file, then crypt is and delete the temporary uncrypted file. This is my encryption sub, the error line occurs on the last line.
Sub EncryptFile(ByVal sInputFilename As String, _
ByVal sOutputFilename As String, _
ByVal sKey As String)
Dim fsInput As New FileStream(sInputFilename, _
FileMode.Open, FileAccess.Read)
Dim fsEncrypted As New FileStream(sOutputFilename, _
FileMode.Create, FileAccess.Write)
Dim DES As New DESCryptoServiceProvider()
'Set secret key for DES algorithm.
'A 64-bit key and an IV are required for this provider.
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
'Set the initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
'Create the DES encryptor from this instance.
Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
'Create the crypto stream that transforms the file stream by using DES encryption.
Dim cryptostream As New CryptoStream(fsEncrypted, _
desencrypt, _
CryptoStreamMode.Write)
'Read the file text to the byte array.
Dim bytearrayinput(fsInput.Length - 1) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
'Write out the DES encrypted file.
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
System.IO.File.Delete(sInputFilename)
End Sub
Can anyone help me out with this? I can't figure out what I am doing wrong.
Use fsInput.Close() right before System.IO.File.Delete(sInputFilename)
Hope this helps

Overflow error for encryption

I am getting an overflow error in the following code:
Public Shared Function AESFileEncrypt(inputFilename As String, outputFilename As String) As Boolean
'Create SymmetricAlgorithm object and specify the Key and IV.
Dim AES As RijndaelManaged = New RijndaelManaged
AES.Key = objKeys.aesKey
AES.IV = objKeys.aesIV
'Create an ICryptoTransform (Encryptor) object.
Dim Encryptor As ICryptoTransform
Encryptor = AES.CreateEncryptor
'Read the unencrypted file.
Dim InputFileStream As FileStream
InputFileStream = New FileStream(inputFilename, FileMode.Open, FileAccess.Read)
Dim InputFileData(CType(InputFileStream.Length, Integer)) As Byte
InputFileStream.Read(InputFileData, 0, CType(InputFileStream.Length, Integer))
Dim OutputFileStream As FileStream
OutputFileStream = New FileStream(outputFilename, FileMode.Create, FileAccess.Write)
'Create a CryptoStream object using the Stream and ICryptoTransform objects.
Dim EncryptCryptoStream As CryptoStream
EncryptCryptoStream = New CryptoStream(OutputFileStream, Encryptor, CryptoStreamMode.Write)
EncryptCryptoStream.Write(InputFileData, 0, InputFileData.Length)
EncryptCryptoStream.FlushFinalBlock()
'Clear any sensitive data from the cyptographic object.
AES.Clear()
'Close stream objects.
EncryptCryptoStream.Close()
InputFileStream.Close()
OutputFileStream.Close()
Return True
'Catch ex As Exception
'Debug.Print("AESFileEncrypt", ex.Message)
'Return False
'End Try
End Function
The error is at this line:
Dim InputFileData(CType(InputFileStream.Length, Integer)) As Byte
This happens on large files. I know it is because the byte array cannot be that large. Can I please have some help to modify this code to get it working?
Thanks
EDIT
This is my current work on this function:
Public Function AESFileEncrypt(inputFilename As String, outputFilename As String, Password As String, Salt As String) As Boolean
Dim AES As RijndaelManaged = New RijndaelManaged
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
Dim PasswordIterations As String = 2
Dim InitialVector As String = "WinStorePassword" '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 PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
Dim Encryptor As ICryptoTransform
Encryptor = AES.CreateEncryptor(KeyBytes, InitialVectorBytes)
Dim InputFileStream As FileStream
InputFileStream = New FileStream(inputFilename, FileMode.Open, FileAccess.Read)
Dim OutputFileStream As FileStream
OutputFileStream = New FileStream(outputFilename, FileMode.Create, FileAccess.Write)
Dim EncryptCryptoStream As CryptoStream
EncryptCryptoStream = New CryptoStream(OutputFileStream, Encryptor, CryptoStreamMode.Write)
Const BUFFER_SIZE As Integer = 4096
Dim buffer(BUFFER_SIZE - 1) As Byte
Dim Position As Long
Do
If (Position + BUFFER_SIZE) > InputFileStream.Length Then
InputFileStream.Read(buffer, Position, InputFileStream.Length - Position)
EncryptCryptoStream.Write(buffer, Position, BUFFER_SIZE)
Exit Do
Else
InputFileStream.Read(buffer, Position, BUFFER_SIZE)
EncryptCryptoStream.Write(buffer, Position, BUFFER_SIZE)
End If
Position += BUFFER_SIZE
Loop
EncryptCryptoStream.FlushFinalBlock()
AES.Clear()
EncryptCryptoStream.Close()
InputFileStream.Close()
OutputFileStream.Close()
Return True
End Function
Is this correct? I did a test an a small file, and the output was a lot larger than i expected?