淺析VB.NET編寫DEC加密程序
學(xué)習(xí)VB.NET時(shí),你可能會(huì)遇到VB.NET編寫DEC加密程序問題,這里將介紹VB.NET編寫DEC加密程序問題的解決方法,在這里拿出來和大家分享一下。
在VB.NET編寫DEC加密程序是很容易的事情,因?yàn)閂B.NET的類庫中就自帶了相應(yīng)的函數(shù),下面分別是加密函數(shù)和解密函數(shù)。
加密函數(shù):
- Public Shared Function Encrypt(ByVal pToEncrypt As String,
ByVal sKey As String) As String- Dim des As New DESCryptoServiceProvider()
- Dim inputByteArray() As Byte
- inputByteArray = Encoding.Default.GetBytes(pToEncrypt)
- ''建立加密對(duì)象的密鑰和偏移量
- ''原文使用ASCIIEncoding.ASCII方法的GetBytes方法
- ''使得輸入密碼必須輸入英文文本
- des.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
- des.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
- ''寫二進(jìn)制數(shù)組到加密流
- ''(把內(nèi)存流中的內(nèi)容全部寫入)
- Dim ms As New System.IO.MemoryStream()
- Dim cs As New CryptoStream(ms, des.CreateEncryptor, CryptoStreamMode.Write)
- ''寫二進(jìn)制數(shù)組到加密流
- ''(把內(nèi)存流中的內(nèi)容全部寫入)
- cs.Write(inputByteArray, 0, inputByteArray.Length)
- cs.FlushFinalBlock()
- ''建立輸出字符串
- Dim ret As New StringBuilder()
- Dim b As Byte
- For Each b In ms.ToArray()
- ret.AppendFormat("{0:X2}", b)
- Next
- Return ret.ToString()
- End Function
解密函數(shù):
- Public Shared Function Decrypt(ByVal pToDecrypt As String,
ByVal sKey As String) As String- Dim des As New DESCryptoServiceProvider()
- ''把字符串放入byte數(shù)組
- Dim len As Integer
- len = pToDecrypt.Length / 2 - 1
- Dim inputByteArray(len) As Byte
- Dim x, i As Integer
- For x = 0 To len
- i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)
- inputByteArray(x) = CType(i, Byte)
- Next
- ''建立加密對(duì)象的密鑰和偏移量,此值重要,不能修改
- des.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
- des.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
- Dim ms As New System.IO.MemoryStream()
- Dim cs As New CryptoStream(ms, des.CreateDecryptor,
CryptoStreamMode.Write)- cs.Write(inputByteArray, 0, inputByteArray.Length)
- cs.FlushFinalBlock()
- Return Encoding.Default.GetString(ms.ToArray)
- End Function
兩個(gè)函數(shù)中***個(gè)參數(shù)是待加密或解密的字符串,sKey是使用的密鑰,必須是8位,使用的時(shí)候要注意哦,不然會(huì)出錯(cuò)的。以上介紹VB.NET編寫DEC加密程序。
【編輯推薦】