2020年5月5日 星期二

VB.NET編寫DES加密程式 [Encrypt with DES]


VB.NET中編寫DEC加密程式是很容易的事情,因為VB.NET的類庫中就自帶了相應的函數,下面分別是加密函數和解密函數。
加密函數:
  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)
  ''建立加密物件的金鑰和偏移量
  ''原文使用ASCIIEncoding.ASCII方法的GetBytes方法
  ''使得輸入密碼必須輸入英文文本
  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.CreateEncryptor CryptoStreamMode.Write)
  ''寫二進位數字組到加密流
  ''(把記憶體流中的內容全部寫入)
  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("{0X2}" b)
  Next
  Return ret.ToString()
  End Function
  ------------------------------------------------------------------
  解密函數:
  Public Shared Function Decrypt(ByVal pToDecrypt As String ByVal sKey As String) As String
  Dim des As New DESCryptoServiceProvider()
  ''把字串放入byte陣列
  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
  ''建立加密物件的金鑰和偏移量,此值重要,不能修改
  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
  -------------------------------------------
  兩個函數中第一個參數是待加密或解密的字串,sKey是使用的金鑰,必須是8位,使用的時候要注意哦,不然會出錯的。

沒有留言:

張貼留言