I've been looking for a while for the right code to encrypt/decrypt files with AES in vb.net. I created the code below. Is this the right way doing AES encryption/decryption nowadays?
Public Function EncryptFile(ByVal plainFilePath As String, ByVal encryptedFilePath As String, ByVal EncryptionKey As String, ByVal SaltValue As String) As String
Dim passwordIterations As Integer = 1000
Dim initVector As String = "Bla3212EWMND12es"
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(SaltValue)
Dim k1 As New Rfc2898DeriveBytes(EncryptionKey, saltValueBytes, passwordIterations)
Dim symmetricKey As New RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(k1.GetBytes(16), initVectorBytes)
Using plain As FileStream = File.Open(plainFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)
Using encrypted As FileStream = File.Open(encryptedFilePath, FileMode.Create, FileAccess.Write, FileShare.None)
Using cs As CryptoStream = New CryptoStream(encrypted, encryptor, CryptoStreamMode.Write)
plain.CopyTo(cs)
End Using
End Using
End Using
End Function
Public Function DecryptFile(ByVal plainFilePath As String, ByVal encryptedFilePath As String, ByVal DecryptionKey As String, ByVal SaltValue As String) As String
Dim passwordIterations As Integer = 1000
Dim initVector As String = "Bla3212EWMND12es"
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(SaltValue)
Dim k1 As New Rfc2898DeriveBytes(DecryptionKey, saltValueBytes, passwordIterations)
Dim symmetricKey As New RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(k1.GetBytes(16), initVectorBytes)
Using plain As FileStream = File.Open(plainFilePath, FileMode.Create, FileAccess.Write, FileShare.None)
Using encrypted As FileStream = File.Open(encryptedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)
Using cs As CryptoStream = New CryptoStream(plain, decryptor, CryptoStreamMode.Write)
encrypted.CopyTo(cs)
End Using
End Using
End Using
End Function