0

早上好,我正在尝试使用 System.Security.Cryptography.RjindaelManaged 进行基本加密。我有谷歌这个错误,找不到问题,或者我做错了什么。我要做的就是加密一个字符串,然后解密一个字符串。

以下是我的代码,任何帮助将不胜感激。

Imports System.Security.Cryptography
Imports System.Text
Public rj As New RijndaelManaged
    Try
        rj.Padding = PaddingMode.None
        rj.GenerateKey()
        rj.GenerateIV()
        Dim curProvider As New AesCryptoServiceProvider
        Dim curEncryptor As ICryptoTransform
        Dim memEncStream As New MemoryStream
        Dim cryptoEncStream As CryptoStream
        curEncryptor = curProvider.CreateEncryptor(rj.Key, rj.IV)
        cryptoEncStream = New CryptoStream(memEncStream, curEncryptor, CryptoStreamMode.Write)
        Dim startingBytes() As Byte = Encoding.ASCII.GetBytes("This is a test")
        Debug.Print("before length: " & startingBytes.Length)
        Debug.Print("before text: " & Encoding.ASCII.GetString(startingBytes))
        EcryptoEncStream.Write(startingBytes, 0, startingBytes.Length)
        cryptoEncStream.FlushFinalBlock()
        memEncStream.Position = 0
        Dim theBytes(memEncStream.Length) As Byte
        memEncStream.Read(theBytes, 0, memEncStream.Length)
        memEncStream.Flush()
        memEncStream.Close()
        cryptoEncStream.Close()
        Debug.Print("How long? " & theBytes.Length)
        Debug.Print("Data: " & Encoding.ASCII.GetString(theBytes))
        Dim curDecryptor As ICryptoTransform
        curDecryptor = curProvider.CreateDecryptor(rj.Key, rj.IV)
        Dim memDecStream As New MemoryStream
        Dim cryptoDecStream As CryptoStream
        curDecryptor = curProvider.CreateDecryptor(rj.Key, rj.IV)
        cryptoDecStream = New CryptoStream(memDecStream, curDecryptor, CryptoStreamMode.Write)
        Dim endingBytes() As Byte = theBytes
        Debug.Print("before length: " & theBytes.Length)
        Debug.Print("before text: " & Encoding.ASCII.GetString(theBytes))
        cryptoDecStream.Write(theBytes, 0, theBytes.Length)
        cryptoDecStream.FlushFinalBlock()
        memDecStream.Position = 0
        Dim endBytes(memDecStream.Length) As Byte
        memDecStream.Read(theBytes, 0, memDecStream.Length)
        memDecStream.Flush()
        memDecStream.Close()
        cryptoEncStream.Close()
        Debug.Print("How long? " & endBytes.Length)
        Debug.Print("Data: " & Encoding.ASCII.GetString(endBytes))
    Catch ex As Exception
        Debug.Print(ex.ToString)
    End Try
4

2 回答 2

1

您已经覆盖了 PaddingMode 并设置了它None。为什么?将 PaddingMode 保留为其默认值,PaddingMode.PKCS7除非您有充分的理由更改它并且您了解分组密码中的填充。

于 2010-01-16T12:20:19.913 回答
0

看来问题在于您传递给解密流的数据的长度。如果您theBytes从此更改声明:

Dim theBytes(memEncStream.Length) As Byte

对此:

Dim theBytes(memEncStream.Length - 1) As Byte

然后它运行良好(至少它对我有用)。我根本不是 VB 向导,但我认为数组声明比给定大小长一个字节(我认为它是 0 到 N)。将额外的字节传递给解密流后,它就不起作用了。

而且我相信您很快就会看到它,但是您打印的最终解密文本并不完全正确。它正在打印theBytes而不是endBytes.

于 2010-01-16T17:01:44.957 回答