1.添加模块
2.复制代码
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO
Module gFunction
'DES加密
Public Function Encrypt(ByVal pToEncrypt As String, ByVal sKey As String) As String
Dim des As New DESCryptoServiceProvider 'DES算法
Dim inputByteArray As Byte()
inputByteArray = Encoding.Default.GetBytes(pToEncrypt)
des.Key = Encoding.UTF8.GetBytes(sKey) 'myKey DES用8个字符,TripleDES要24个字符
des.IV = Encoding.UTF8.GetBytes(sKey)
Dim ms As New MemoryStream
Dim cs As New CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)
Dim sw As New StreamWriter(cs)
sw.Write(pToEncrypt)
sw.Flush()
cs.FlushFinalBlock()
ms.Flush()
Encrypt = Convert.ToBase64String(ms.GetBuffer(), 0, ms.Length)
End Function
'DES解密
Public Function Decrypt(ByVal pToDecrypt As String, ByVal sKey As String) As String
Dim des As New DESCryptoServiceProvider 'DES算法
des.Key = Encoding.UTF8.GetBytes(sKey) 'myKey DES用8个字符,TripleDES要24个字符
des.IV = Encoding.UTF8.GetBytes(sKey)
Dim buffer As Byte() = Convert.FromBase64String(pToDecrypt)
Dim ms As New MemoryStream(buffer)
Dim cs As New CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)
Dim sr As New StreamReader(cs)
Decrypt = sr.ReadToEnd()
End Function
End Module
3.调用
加密:Encrypt(Label1.Text, "qclghf21")
解密:Decrypt("原字符串", "12345678")
注意其中des.Key与des.IV 可以不同 我这里为了省事就直接这样进行了
可参考此资料 https://blog.csdn.net/lpwmm/article/details/50816153