Visual Basic 8 (2005)WebFormsVisual Studio 2005.NET 2.0中级开发Visual StudioWindows.NETVisual BasicASP.NET
加密带超时的查询字符串






4.16/5 (6投票s)
创建一个加密且过期的查询字符串。
引言
这是一个对多个加密和密码更改文章的增强和“混合”。问题在于,我需要一种不仅加密,而且易于实现且具有过期时间的方案。
背景
几个月前,我使用 Visual Studio 2005 中的 ASP.NET 会员控件实现了一个应用程序。该实现的一部分允许密码恢复。我面临的问题是,发回给用户的密码非常奇怪,而且整个过程有点繁琐。在互联网上查找后,我发现了一种基于从电子邮件推送链接来重置密码的方法。这种方法的缺点是,如果有人在使用后不删除电子邮件,或者如果有人可以解释用户 ID,则密码可能会在未经授权或知情的情况下被重置。因此,我创建了一个小类,解决了这些问题。本质上,它获取一个加密密钥以及用户名和时间戳,并创建一个包含加密密钥的 URL。
解密部分获取 URL,并使用加密密钥验证日期和时间戳是否仍然有效。如果是,那么您可以假设这是用户在几分钟内的操作。我建议将长度设置为不超过 30 分钟,但它是可配置的。
在这个文件中,我还附上了一个小示例应用程序,演示了如何实现它。一旦你掌握了它,就可以将其用于几乎任何事情。如果有更好的方法或评论,请告诉我。
Using the Code
下载代码并打开加密类。它包含三个属性和两个 public
函数。
这些属性是
//
Public Property UserName() As String
Get
Return m_username
End Get
Set(ByVal value As String)
m_username = value
End Set
End Property
Public Property EncryptionKey() As String
Get
Return m_EncryptionKey
End Get
Set(ByVal value As String)
m_EncryptionKey = value
End Set
End Property
Public Property ExpireDateTime() As DateTime
Get
Return m_ExpireDateTime
End Get
Set(ByVal value As DateTime)
m_ExpireDateTime = value
End Set
End Property
//
这两个 public
类是
Public Function Encrypt() As String
If String.IsNullOrEmpty(m_EncryptionKey) Then
Throw New Exception("Encryption Key is Required")
End If
'Ensure that timeStampKey exists and update the expiration time.
If String.IsNullOrEmpty(m_ExpireDateTime.ToString) Then
Throw New Exception("Expiration Date is Required")
End If
Dim buffer() As Byte = Encoding.ASCII.GetBytes(serialize())
Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
Dim MD5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(m_EncryptionKey))
des.IV = IV
Return Convert.ToBase64String(des.CreateEncryptor.TransformFinalBlock_
(buffer, 0, buffer.Length))
End Function
Public Function Decrypt(ByVal EncryptedUsername As String) As String
If String.IsNullOrEmpty(m_EncryptionKey) Then
Throw New Exception("Encryption Key is not set")
End If
Try
Dim buffer() As Byte = Convert.FromBase64String(EncryptedUsername)
Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
Dim MD5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(m_EncryptionKey))
des.IV = IV
deserialize(Encoding.ASCII.GetString_
(des.CreateDecryptor.TransformFinalBlock(buffer, 0, buffer.Length)))
Return Encoding.ASCII.GetString(des.CreateDecryptor.TransformFinalBlock_
(buffer, 0, buffer.Length))
Catch ex As CryptographicException
Throw New Exception("Crypto error")
Catch ex As FormatException
Throw New Exception("FormatExpection")
End Try
End Function
关注点
这段代码来自本网站上的几篇文章,并结合起来创建了这个类。这些文章如下:密码恢复 和 防篡改查询字符串 以及一些原始代码。
历史
- 2007.08.22 - 版本 1 (初始上传)