第1部分:应用场景
我们在开发应用的过程中,
少不了使用应用程序的配置文件,
因为这样可以增加程序的灵活性,
但是这一做法存在一个危险,
就是被有心者且稍微了解配置文件的人篡改,
或者获取到我们需要保密的信息,
基于此,我们只能对这些字符串进行加密,
而在使用的时候解密,
这样既能保证程序的灵活性又不降低安全性。
第2部分:源代码
Imports System.Security.Cryptography Imports System.IO Imports System.Text Public Class Form1 rem 调用加密过程 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim MyStringBefor As String = TextBox1.Text Dim rr As New MyDES Dim MyStringAfter As String = rr.CodeInface(MyStringBefor) TextBox2.Text = MyStringAfter Catch ex As Exception MsgBox(ex.Message.ToString) End Try End Sub rem 调用解密过程 Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try Dim MyStringAfter As String = TextBox2.Text Dim rr As New MyDES Dim MyStringBefor As String = rr.CodeOutface(MyStringAfter) TextBox1.Text = MyStringBefor Catch ex As Exception MsgBox(ex.Message.ToString) End Try End Sub End Class Public Class MyDES Private I(24) As Byte Private Iv(24) As Byte Friend Function CodeInface(ByVal intxt As String) As String Dim cryptoProvider As TripleDESCryptoServiceProvider Dim ms As MemoryStream Dim cs As CryptoStream Dim sw As StreamWriter cryptoProvider = New TripleDESCryptoServiceProvider ms = New MemoryStream cs = New CryptoStream(ms, cryptoProvider.CreateEncryptor(I, Iv), CryptoStreamMode.Write) sw = New StreamWriter(cs) sw.Write(intxt) sw.Flush() cs.FlushFinalBlock() ms.Flush() Return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length)) End Function Friend Function CodeOutface(ByVal outtxt As String, Optional ByVal bCry As Boolean = False) As String If outtxt = "" And Not bCry Then Return "" Dim cryTxt() As Byte Dim textConverter As ASCIIEncoding Dim cryptoProvider As TripleDESCryptoServiceProvider Dim ms As MemoryStream Dim cs As CryptoStream Dim sw As StreamReader textConverter = New ASCIIEncoding cryptoProvider = New TripleDESCryptoServiceProvider cryTxt = Convert.FromBase64String(outtxt) ms = New MemoryStream(cryTxt) cs = New CryptoStream(ms, cryptoProvider.CreateDecryptor(I, Iv), CryptoStreamMode.Read) sw = New StreamReader(cs) Return sw.ReadToEnd() End Function rem 定义位,可以修改,相当于更改加密方法 Public Sub New() I = New Byte() {149, 19, 93, 156, 178, 4, 220, 232, 65, 167, 43, 80, 26, 230, 155, 112, 70, 94, 11, 204, 2, 35, 184, 97} Iv = New Byte() {152, 123, 206, 179, 236, 200, 167, 43, 242, 66, 92, 83, 124, 57, 19, 13, 145, 23, 200, 58, 173, 10, 121, 120} End Sub End Class
第3部分:结论
通过上面这个源代码,能够很好的实现加密、解密过程
并且加密解密过程可以通过修改位来更改你的加密、解密方式,
具有很好的灵活性,希望各位一起探讨
Csharp(c#.net)的做法请参考我的另一篇文章:《Csharp(C#.net)中如何对字符串进行TripleDESCryptoServiceProvider加密,确保程序安全》
© 版权声明
THE END
暂无评论内容