VB.net编程教程:编写文字加解密程序(2)
介绍部分常用的枚举进入csmode.vb类的代码事件
输入代码:
Imports System
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public Class csmode
Public Function Encrypt(ByVal StrInput As String) As String
Dim ByteInput As [Byte]() = Encoding.Default.GetBytes(StrInput)
Dim ms As New System.IO.MemoryStream
Dim DESC As New DESCryptoServiceProvider
Dim CStream As New CryptoStream(ms, DESC.CreateEncryptor(Encoding.Default.GetBytes("20000000"), Encoding.Default.GetBytes("字节数量")), CryptoStreamMode.Write)
CStream.Write(ByteInput, 0, ByteInput.Length)
CStream.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
End Function
Public Function Decrypt(ByVal StrInput As String) As String
Dim ByteInput As [Byte]() = Convert.FromBase64String(StrInput)
Dim ms As New System.IO.MemoryStream
Dim DESC As New DESCryptoServiceProvider
Dim CStream As New CryptoStream(ms, DESC.CreateDecryptor(Encoding.Default.GetBytes("20000000"), Encoding.Default.GetBytes("字节数量")), CryptoStreamMode.Write)
CStream.Write(ByteInput, 0, ByteInput.Length)
CStream.FlushFinalBlock()
Return Encoding.Default.GetString(ms.ToArray())
End Function
End Class
选择Form1窗体,进入代码编辑器
首先进行声明
Imports System
Imports System.IO
Imports System.Text
Public Class Form1
Inherits System.Windows.Forms.Form
进入Button1_Click事件
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Encode As New csmode() '对文字进行加密
TextBox2.Text = Encode.Encrypt(TextBox1.Text)
End Sub
进入Button2_Click事件
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim Decode As New csmode() '对文字进行解密
TextBox3.Text = Decode.Decrypt(TextBox2.Text)
End Sub
代码输入完毕,接下来运行程序进行测试。如图4
程序运行成功,以上是一个简单的文字加密与解密程序的编写过程,希望大家可以举一反三,利用这种思路可以编写出功能更强大的加解密程序。