I'm trying to from read a .txt file and and then decrypt a line to use in My.Settings but I keep getting 'Padding is invalid and cannot be removed' error in the decryption, heres the code I use
Code:
Public Function Decrypt(ByVal cipherText As String) As String
Dim passPhrase As String = "x"
Dim saltValue As String = "x"
Dim hashAlgorithm As String = "SHA1"
Dim passwordIterations As Integer = 2
Dim initVector As String = "#xxxxxxxxxxxxxxx"
Dim keySize As Integer = 256
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)
Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
Dim symmetricKey As New RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
Dim memoryStream As New MemoryStream(cipherTextBytes)
Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
memoryStream.Close()
cryptoStream.Close()
Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)
Return plainText
End Function
Public Function GetSettingItem(ByVal File As String, ByVal Identifier As String) As String
Dim S As New IO.StreamReader(File) : Dim Result As String = ""
Do While (S.Peek <> -1)
Dim Line As String = S.ReadLine
If Line.ToLower.StartsWith(Identifier.ToLower & ":") Then
Result = Line.Substring(Identifier.Length + 2)
End If
Loop
Return Result
End Function
Private Sub FrmMainMenu_Load(sender As Object, e As EventArgs) Handles MyBase.Load
My.Settings.X = Decrypt(GetSettingItem(SettingsPath, "X"))
End Sub