加密和解密字符串 - Visual Basic

本演练演示如何使用 TripleDES 类通过三重数据加密标准(3DES)算法加密和解密字符串。 第一步是创建一个简单的包装类,该类封装 3DES 算法并将加密数据存储为 base-64 编码字符串。 然后,该包装器用于安全地将专用用户数据存储在可公开访问的文本文件中。

可以使用加密来保护用户机密(例如密码),并使未经授权的用户无法读取凭据。 这可以防止授权用户的标识被盗,从而保护用户的资产并提供不可否认性。 加密还可以保护用户的数据不被未经授权的用户访问。

有关更多信息,请参阅加密服务。

重要

Rijndael(现在称为高级加密标准 [AES])和三重数据加密标准 (3DES) 算法提供比 DES 更高的安全性,因为它们在计算上更密集。 有关详细信息,请参阅 DES 和 Rijndael。

创建加密包装器

Simple3Des创建类以封装加密和解密方法。

Public NotInheritable Class Simple3Des

End Class

将加密命名空间的导入添加到包含 Simple3Des 该类的文件的开头。

Imports System.Security.Cryptography

在 Simple3Des 类中,添加一个专用字段来存储 3DES 加密服务提供程序。

Private TripleDes As TripleDES = TripleDES.Create()

添加一个私有方法,该方法从指定键的哈希创建指定长度的字节数组。

Private Function TruncateHash(

ByVal key As String,

ByVal length As Integer) As Byte()

Using sha256 As SHA256 = SHA256.Create()

' Hash the key.

Dim keyBytes() As Byte =

System.Text.Encoding.Unicode.GetBytes(key)

Dim hash() As Byte = sha256.ComputeHash(keyBytes)

' Truncate or pad the hash.

ReDim Preserve hash(length - 1)

Return hash

End Using

End Function

添加构造函数以初始化 3DES 加密算法。

参数 key 控制 EncryptData 方法和 DecryptData 方法。

Sub New(ByVal key As String)

' Initialize the crypto provider.

TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8)

TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8)

End Sub

添加加密字符串的公共方法。

Public Function EncryptData(

ByVal plaintext As String) As String

' Convert the plaintext string to a byte array.

Dim plaintextBytes() As Byte =

System.Text.Encoding.Unicode.GetBytes(plaintext)

' Create the stream.

Dim ms As New System.IO.MemoryStream

' Create the encoder to write to the stream.

Dim encStream As New CryptoStream(ms,

TripleDes.CreateEncryptor(),

System.Security.Cryptography.CryptoStreamMode.Write)

' Use the crypto stream to write the byte array to the stream.

encStream.Write(plaintextBytes, 0, plaintextBytes.Length)

encStream.FlushFinalBlock()

' Convert the encrypted stream to a printable string.

Return Convert.ToBase64String(ms.ToArray)

End Function

添加解密字符串的公共方法。

Public Function DecryptData(

ByVal encryptedtext As String) As String

' Convert the encrypted text string to a byte array.

Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext)

' Create the stream.

Dim ms As New System.IO.MemoryStream

' Create the decoder to write to the stream.

Dim decStream As New CryptoStream(ms,

TripleDes.CreateDecryptor(),

System.Security.Cryptography.CryptoStreamMode.Write)

' Use the crypto stream to write the byte array to the stream.

decStream.Write(encryptedBytes, 0, encryptedBytes.Length)

decStream.FlushFinalBlock()

' Convert the plaintext stream to a string.

Return System.Text.Encoding.Unicode.GetString(ms.ToArray)

End Function

包装类现在可用于保护用户资产。 在此示例中,它用于安全地将专用用户数据存储在可公开访问的文本文件中。

测试加密包装器

在单独的类中,添加一个方法,该方法使用包装器 EncryptData 的方法加密字符串并将其写入用户的“我的文档”文件夹。

Sub TestEncoding()

Dim plainText As String = InputBox("Enter the plain text:")

Dim password As String = InputBox("Enter the password:")

Dim wrapper As New Simple3Des(password)

Dim cipherText As String = wrapper.EncryptData(plainText)

MsgBox("The cipher text is: " & cipherText)

My.Computer.FileSystem.WriteAllText(

My.Computer.FileSystem.SpecialDirectories.MyDocuments &

"\cipherText.txt", cipherText, False)

End Sub

添加从用户的“我的文档”文件夹中读取加密字符串的方法,并使用包装器 DecryptData 的方法解密该字符串。

Sub TestDecoding()

Dim cipherText As String = My.Computer.FileSystem.ReadAllText(

My.Computer.FileSystem.SpecialDirectories.MyDocuments &

"\cipherText.txt")

Dim password As String = InputBox("Enter the password:")

Dim wrapper As New Simple3Des(password)

' DecryptData throws if the wrong password is used.

Try

Dim plainText As String = wrapper.DecryptData(cipherText)

MsgBox("The plain text is: " & plainText)

Catch ex As System.Security.Cryptography.CryptographicException

MsgBox("The data could not be decrypted with the password.")

End Try

End Sub

添加用户界面代码以调用 TestEncoding 和 TestDecoding 方法。

运行该应用程序。

测试应用程序时,请注意,如果提供错误的密码,则不会解密数据。

另请参阅

System.Security.Cryptography

DESCryptoServiceProvider

DES

TripleDES

Rijndael

加密服务