选择Form1窗体,在Form1窗体中添加如下控件:Label1、Label2、 Label3控件,TextBox1、TextBox2、TextBox3控件,Button1与Button2控件。
相关属性设置如下:
我们适当地调整界面,界面设置效果如下:图2
程序界面设置好后,我们需要创建类,在类中来输入与此程序相关的代码
选择<项目>---<添加类>---文件命名为:csmode 如图3
在编程之前首先我们需要知道System.Security.Cryptography 命名空间
System.Security.Cryptography 命名空间提供加密服务,包括安全的数据编码和解码
介绍部分常用的枚举
介绍部分常用的枚举进入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
程序运行成功,以上是一个简单的文字加密与解密程序的编写过程,希望大家可以举一反三,利用这种思路可以编写出功能更强大的加解密程序。
……