我试图弄清楚如何在 VB.Net 中加密/解密字符串。
我按照此处给出的示例编写了以下代码(如下)。有一个文本框、一个“加密”按钮和一个“解密”按钮。这个想法是在文本框中输入一些东西(“like 'hello world'”),单击“加密”,然后看到加密版本出现在文本框中。然后单击“解密”应将您带回原始字符串。
但是当我尝试加密时,当我尝试“FlushFinalBlock”时出现错误。错误是:“要加密的数据长度无效”。
“解密”部分完全是在黑暗中拍摄,因为上面引用的示例仅处理加密,而不是解密。我确定这是错误的,但由于我无法“加密”工作,我还没有测试它。
谁能告诉我为什么这不起作用?
Imports System.Data.SqlClient
Imports System.IO
Imports System.Security.Cryptography
Public Class Form1
Private cryptObj As RijndaelManaged
Private KEY_128 As Byte() = {42, 1, 52, 67, 231, 13, 94, 101, 123, 6, 0, 12, 32, 91, 4, 111, 31, 70, 21, 141, 123, 142, 234, 82, 95, 129, 187, 162, 12, 55, 98, 23}
Private IV_128 As Byte() = {234, 12, 52, 44, 214, 222, 200, 109, 2, 98, 45, 76, 88, 53, 23, 78}
Private enc As System.Text.UTF8Encoding = New System.Text.UTF8Encoding()
Private Sub btnEncrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEncrypt.Click
Dim sPlainText As String = Me.TextBox1.Text
If Not String.IsNullOrEmpty(sPlainText) Then
Dim bPlainText As Byte() = Me.enc.GetBytes(Me.TextBox1.Text)
Dim ms As MemoryStream = New MemoryStream()
Dim cs As CryptoStream = New CryptoStream(ms, cryptObj.CreateEncryptor(), CryptoStreamMode.Write)
cs.Write(bPlainText, 0, sPlainText.Length)
cs.FlushFinalBlock()
Me.TextBox1.Text = Me.enc.GetString(ms.ToArray())
End If
End Sub
Private Sub btnDecrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDecrypt.Click
Dim sCipherText = Me.TextBox1.Text
Dim ms As MemoryStream = New MemoryStream()
Dim cs As CryptoStream = New CryptoStream(ms, cryptObj.CreateDecryptor(), CryptoStreamMode.Read)
cs.Read(Me.enc.GetBytes(sCipherText), 0, sCipherText.Length)
Me.TextBox1.Text = Me.enc.GetString(ms.ToArray())
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.cryptObj = New RijndaelManaged()
Me.cryptObj.BlockSize = 128
Me.cryptObj.KeySize = 128
Me.cryptObj.Mode = CipherMode.ECB
Me.cryptObj.Padding = PaddingMode.None
Me.cryptObj.Key = KEY_128
Me.cryptObj.IV = IV_128
End Sub
End Class