在VB.NET中,可以使用System.Configuration.ConfigurationManager类来访问web.config文件中的密钥对字段,并进行加密操作。下面是一个示例代码:
Imports System.Configuration
Imports System.Security.Cryptography
Imports System.Text
Public Class EncryptionHelper
Public Shared Function EncryptData(data As String) As String
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim section As AppSettingsSection = DirectCast(config.GetSection("appSettings"), AppSettingsSection)
Dim key As String = section.Settings("EncryptionKey").Value
Dim provider As New AesCryptoServiceProvider()
provider.Key = Encoding.ASCII.GetBytes(key)
provider.Mode = CipherMode.ECB
provider.Padding = PaddingMode.PKCS7
Dim encryptor As ICryptoTransform = provider.CreateEncryptor()
Dim dataBytes As Byte() = Encoding.ASCII.GetBytes(data)
Dim encryptedDataBytes As Byte() = encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length)
Return Convert.ToBase64String(encryptedDataBytes)
End Function
Public Shared Function DecryptData(encryptedData As String) As String
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim section As AppSettingsSection = DirectCast(config.GetSection("appSettings"), AppSettingsSection)
Dim key As String = section.Settings("EncryptionKey").Value
Dim provider As New AesCryptoServiceProvider()
provider.Key = Encoding.ASCII.GetBytes(key)
provider.Mode = CipherMode.ECB
provider.Padding = PaddingMode.PKCS7
Dim decryptor As ICryptoTransform = provider.CreateDecryptor()
Dim encryptedDataBytes As Byte() = Convert.FromBase64String(encryptedData)
Dim decryptedDataBytes As Byte() = decryptor.TransformFinalBlock(encryptedDataBytes, 0, encryptedDataBytes.Length)
Return Encoding.ASCII.GetString(decryptedDataBytes)
End Function
End Class
在上述代码中,EncryptData函数接收一个字符串参数data,它将从web.config文件中获取名为"EncryptionKey"的密钥,并使用AES算法对data进行加密。加密后的数据以Base64字符串的形式返回。
DecryptData函数接收一个加密后的Base64字符串参数encryptedData,它同样从web.config文件中获取密钥,并使用AES算法对encryptedData进行解密。解密后的数据以字符串形式返回。
请注意,上述代码中的"EncryptionKey"是web.config文件中的一个自定义密钥字段,你需要在web.config文件中添加以下内容:
<configuration>
<appSettings>
<add key="EncryptionKey" value="your_encryption_key_here" />
</appSettings>
</configuration>
你需要将"your_encryption_key_here"替换为你自己的密钥。
这是一个简单的示例,你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云