Public Class Form1
Dim charAarray() As Char
‘加密
Private Sub Btn_En_Click(sender As System.Object, e As System.EventArgs) Handles Btn_En.Click
Dim s As String
Dim result As Boolean
result = EncryptOrDecrypt(Txt_PlainText_1.Text, Txt_Secrect_Key.Text, 1, s)
Txt_Text_1.Text = s
MessageBox.Show(IIf(result, "Success", "Failure"))
End Sub
‘解密
Private Sub Btn_De_Click(sender As System.Object, e As System.EventArgs) Handles Btn_De.Click
Dim s As String
Dim result As Boolean
result = EncryptOrDecrypt(Txt_Text_2.Text, Txt_Secrect_Key.Text, -1, s)
Txt_PlainText_2.Text = s
MessageBox.Show(IIf(result, "Success", "Failure"))
End Sub
‘加解密字符串
‘str为待加密的字符串
‘secretKey为秘钥
‘f为加解密标示,f=1标示加密,f=-1标示解密
‘outputStr为加解密之后的字符串
‘返回操作结果
Function EncryptOrDecrypt(ByVal str As String, ByVal secretKey As Integer, ByVal f As Integer, ByRef outputStr As String) As Boolean
outputStr = ""
If (String.IsNullOrWhiteSpace(str)) Then
Return False
End If
Dim c As Char
For i As Integer = 0 To str.Length - 1
c = str(i)
c = EncryptChar(c, secretKey, f)
outputStr &= c
Next i
Return True
End Function
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
charAarray = CreateCharArray()
MessageBox.Show("OK")
End Sub
Function CreateCharArray() As System.Array
Dim s As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
Dim rnd As New Random
Dim cArray(s.Length - 1) As Char
Dim index As Integer
Dim i As Integer
i = 0
Do
index = rnd.Next(s.Length)
If Not cArray.Contains(s(index)) Then
cArray(i) = s(index)
i += 1
End If
Loop While (i < s.Length)
Return cArray
End Function
‘加密单个字符
‘c为要加密的字符
‘secretKey为秘钥
‘f为加解密标示,f=1标示加密,f=-1标示解密
‘返回加密之后的字符
Function EncryptChar(ByVal c As Char, ByVal secretKey As Integer, ByVal f As Integer) As Char
Dim cIndex As Integer
Dim len As Integer
len = charAarray.Length
cIndex = Array.IndexOf(charAarray, c)
If f = 1 Then
cIndex += secretKey
Else
cIndex -= secretKey
End If
If (cIndex >= len) Then
Math.DivRem(cIndex, len, cIndex)
End If
If (cIndex < 0) Then
Do
cIndex += len
Loop While (cIndex < 0)
End If
Return charAarray(cIndex)
End Function
End Class