将ListBox项加密/解密为Base64或TripleDES

时间:2015-03-05 21:27:31

标签: vb.net encryption base64 tripledes

我想将ListBox文本字符串加密和解密为Base64或TripleDES 我尝试使用TripleDES,但我不知道如何使它与ListBoxes一起使用 这是我使用的代码:

TripleDES课程:

Imports System.Security.Cryptography                                                                         Public NotInheritable Class PassEncryption
Private TripleDes As New TripleDESCryptoServiceProvider
Private Function TruncateHash(
ByVal key As String,
ByVal length As Integer) As Byte()
    Dim sha1 As New SHA1CryptoServiceProvider
    Dim keyBytes() As Byte =
        System.Text.Encoding.Unicode.GetBytes(key)
    Dim hash() As Byte = sha1.ComputeHash(keyBytes)
    ReDim Preserve hash(length - 1)
    Return hash
End Function
Sub New(ByVal key As String)
    TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8)
    TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8)
End Sub
Public Function EncryptData(
ByVal plaintext As String) As String
    Dim plaintextBytes() As Byte =
        System.Text.Encoding.Unicode.GetBytes(plaintext)
    Dim ms As New System.IO.MemoryStream
    Dim encStream As New CryptoStream(ms,
        TripleDes.CreateEncryptor(),
        System.Security.Cryptography.CryptoStreamMode.Write)
    encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
    encStream.FlushFinalBlock()
    Return Convert.ToBase64String(ms.ToArray)
End Function
Public Function DecryptData(ByVal encryptedtext As String) As String
    Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext)
    Dim ms As New System.IO.MemoryStream
    Dim decStream As New CryptoStream(ms,
        TripleDes.CreateDecryptor(),
        System.Security.Cryptography.CryptoStreamMode.Write)
    decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
    decStream.FlushFinalBlock()
    Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
End Function
End Class

实际使用: 加密:

        For Each item As String In ListBox1.Items`
        Dim EncodePassword As String = item
        Dim key As String = My.Computer.Info.OSFullName
        Dim wrapper As New PassEncryption(key)
        Dim cipherText As String = wrapper.EncryptData(EncodePassword)
TextBox2.Text = cipherText
Using SW1 As New IO.StreamWriter(Application.StartupPath & "\Encoded.txt", True)

        SW1.WriteLine(TextBox2.Text)

    End Using

解密:

Dim cipherText As String = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Encoded.txt")
        Dim key As String = My.Computer.Info.OSFullName
        Dim wrapper As New PassEncryption(key)
            Dim DecodedPassword As String = wrapper.DecryptData(cipherText)
            TextBox2.Text = DecodedPassword

那么,如何使用此算法或其他算法(p.e Base64)加密/解密ListBox?

0 个答案:

没有答案