尝试解密时Base-64字符串中的字符无效
问题描述:
我有一种加密/解密方法,可以正常工作,但有一个例外。当我尝试从文本文件中读取加密文本并解密时,出现以下错误。尝试解密时Base-64字符串中的字符无效
Invalid character in a Base-64 string
奇怪的是,如果我刚才读的加密文本到文本框,然后将其复制并佩特成解密使用它工作得很好相同解密方法另一个文本框。没有错误和解密进行。我列出了用于在下面的文本文件中读取的解密方法和方法。
解密方法
Public Shared Function DecryptUserString(ByRef cipheredText As String, ByRef password As String) As String
Dim RijndaelManagedObj As New RijndaelManaged
Dim RijndaelEncObj As ICryptoTransform, MD5Obj As New MD5CryptoServiceProvider
Dim DecryptedBytes As Byte(), EncryptedData As Byte()
Dim PasswordBytes As Byte() = New ASCIIEncoding().GetBytes(password)
Dim UTF8Encoding As System.Text.Encoding = System.Text.Encoding.UTF8
'A modified Base64 is sent with ~ and - so it can be sent as a form post
EncryptedData = Convert.FromBase64String(Replace(Replace(cipheredText, "~", "+"), "-", "="))
RijndaelManagedObj.BlockSize = 128
RijndaelManagedObj.KeySize = 128
RijndaelManagedObj.Mode = CipherMode.ECB
RijndaelManagedObj.Padding = PaddingMode.None
RijndaelManagedObj.Key = MD5Obj.ComputeHash(PasswordBytes)
RijndaelEncObj = RijndaelManagedObj.CreateDecryptor()
DecryptedBytes = RijndaelEncObj.TransformFinalBlock(EncryptedData, 0, EncryptedData.Length)
If DecryptedBytes.Length > 0 Then
DecryptUserString = UTF8Encoding.GetString(DecryptedBytes, 0, DecryptedBytes.Length)
If DecryptedBytes.Length = 0 Then DecryptUserString = New ASCIIEncoding().GetString(DecryptedBytes)
Else
DecryptUserString = ""
End If
End Function
方法从文件中读取文本
Private Function ReadText(ByVal TextFilePath As String) As String
Using ReadStream As FileStream = File.OpenRead(TextFilePath)
Dim FileTextBuilder As New StringBuilder()
Dim DataTransit As Byte() = New Byte(ReadStream.Length) {}
Dim DataEncoding As New UTF8Encoding(True)
While ReadStream.Read(DataTransit, 0, DataTransit.Length) > 0
FileTextBuilder.Append(DataEncoding.GetString(DataTransit))
End While
Return FileTextBuilder.ToString()
End Using
End Function
答
不能使用File.ReadAllText()方法读取整个文件,然后解密方式与使用文本框相同?
我知道,如果文件很大,这不是一个好主意,但是您可以尝试查看文件是否已妥善保存,或者您是否阅读得不好。
工作正常!我的文件总是小于20k。有需要担心的文件大小吗?再次感谢! – webworm 2011-04-13 16:14:17
@webworm:不,没有“标准”文件大小,你不得不担心...但记住:当你在内存中加载文件时,RAM会被占用......所以文件越大,文件越大消耗的内存量。 – Marco 2011-04-13 17:24:30