The following encrypting/decrypting code works well during saving/opening a text file/stream. But when I close and re-launch my the application, open the previously saved text file through streamreader, and during decryption, error is encountered at decStream.FlushFinalBlock() line saying "Bad Data"... Would appreciate any help, please... thanks!
VB.NET:
Sub iSave_WB()
Dim ioFile As New StreamWriter(iFileName)
With ioFile
.WriteLine(EncryptDataTxt("cboWBMode,0"))
.WriteLine(EncryptDataTxt("dtpActivity," & Format(dtpActivity.Value, "yyyy-MM-dd")))
.WriteLine(EncryptDataTxt("cboRegistration," & cboRegistration.SelectedItem.Col1))
End With
ioFile.Close()
ioFile.Dispose()
End Sub
Private Function DecryptDataTxt(ByVal encryptedTxt As String) As String
Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedTxt)
Dim mStr As New System.IO.MemoryStream
Dim decStream As New CryptoStream(mStr, TripleDes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
decStream.FlushFinalBlock() 'Error is encountered here...
decStream.Close()
Return System.Text.Encoding.Unicode.GetString(mStr.ToArray)
End Function
Private Function EncryptDataTxt(ByVal plainText As String) As String
Dim plaintextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext)
Dim mStr As New System.IO.MemoryStream
Dim encStream As New CryptoStream(mStr, TripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
encStream.FlushFinalBlock()
encStream.Close()
Return Convert.ToBase64String(mStr.ToArray)
End Function
Sub iOpen_WB()
Dim iText() As String = System.IO.File.ReadAllLines(iFileName)
Dim iStr As String, iDecrypted As String
For Each iStr In iText
iDecrypted = DecryptDataTxt(Trim(iStr.Replace(vbCrLf, vbNullChar)))
Dim iCol() As String = iDecrypted.Split(New [Char]() {","c})
iCol(0) = Trim(iCol(0).Replace(vbTab, vbNullString)).Replace(" ", vbNullString)
iCol(1) = Trim(iCol(1).Replace(vbTab, vbNullString)).Replace(" ", vbNullString)
Select Case iCol(0)
Case "cboWBMode"
cboWBMode.SelectedIndex = 0
Case "dtpActivity"
dtpActivity.Value = CDate(iCol(1))
Case "cboRegistration"
cboRegistration.Text = iCol(1)
End Select
Next
Last edited: