我想知道如何通过vb.net代码加密电子邮件地址。
我发现了一个与特殊字符不兼容的示例,我收到此错误:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
以下是我正在尝试的代码:
'The function used to encrypt the text
Private Function Encrypt(ByVal strText As String, ByVal strEncrKey _
As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Try
byKey = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
Dim des As New DESCryptoServiceProvider()
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strText)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
你们觉得怎么样?我究竟做错了什么? 谢谢,Laziale
更新:完整堆栈跟踪:
发现了System.FormatException Message =输入不是有效的Base-64字符串,因为它包含非基本64个字符,两个以上的填充字符或填充字符中的非空白字符。 来源= mscorlib程序 堆栈跟踪: 在System.Convert.FromBase64String(String s) 在D:\ Website \ Account \ Login.aspx.vb的WEbsite.Login.Decrypt(String strText,String sDecrKey):第213行 InnerException:
更新2:
添加了加密方法:
'用于解密文本的函数
Private Function Decrypt(ByVal strText As String, ByVal sDecrKey _
As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Dim inputByteArray(strText.Length) As Byte
Try
byKey = System.Text.Encoding.UTF8.GetBytes(Left(sDecrKey, 8))
Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(strText)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
答案 0 :(得分:1)
我已尝试使用解密作为输入,使用加密文本和相同的密钥。
它按预期工作。我对您的代码所做的唯一更改是使用Substring方法而不是
byKey = System.Text.Encoding.UTF8.GetBytes(strDecrKey.Substring(0, 8))
我用这种方式调用这两种方法:
Dim result as String = Encrypt("test@gmail.com", "ABCD9876")
Dim decrypted = Decrypt(result, "ABCD9876")
我回来了“test@gmail.com” -Buon Weekend anche a te -
答案 1 :(得分:0)
使用String Builder而不是string作为带有特殊字符的参数。
最好的问候。