我目前正在尝试编写一个进程,对以Byte流形式发送的文件进行加密。AES库似乎没有正确地应用padding。
当我试图进行加密时,我得到的密码字节是这样的。
... 50 57 243 226 18 0 0 0 0 0 0 0 0 0 ... (大约有30,000个0加到最后)
当我认为我应该得到这样的密码字节(使用PKCS7)。
... 50 57 243 226 18 9 9 9 9 9 9 9 9 9
如何让实际的padding方法被识别并像PKCS7那样返回padding?
Public Function Encrypt(InputStream As Stream) As Byte()
Dim outputStream = New MemoryStream()
Dim EncryptionKey As String = "MAKV2SPBNI99212"
Using encryptor As Aes = Aes.Create()
Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, &H65, &H64, &H76, &H65, &H64, &H65, &H76})
encryptor.Key = pdb.GetBytes(32)
encryptor.IV = pdb.GetBytes(16)
Using cs As New CryptoStream(outputStream, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
Dim data As Integer
While (Assign(data, InputStream.ReadByte())) <> -1
cs.WriteByte(CByte(data))
End While
End Using
End Using
Return outputStream.GetBuffer()
End Function
Public Function Decrypt(InputStream As Stream) As Byte()
Dim outputStream = New MemoryStream()
Dim EncryptionKey As String = "MAKV2SPBNI99212"
Using encryptor As Aes = Aes.Create()
Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, &H65, &H64, &H76, &H65, &H64, &H65, &H76})
encryptor.Key = pdb.GetBytes(32)
encryptor.IV = pdb.GetBytes(16)
Using cs As New CryptoStream(InputStream, encryptor.CreateDecryptor(), CryptoStreamMode.Read)
Dim data As Integer
While (Assign(data, cs.ReadByte())) <> -1
outputStream.WriteByte(CByte(data))
End While
End Using
End Using
Return outputStream.GetBuffer
End Function
Private Function Assign(Of T)(ByRef source As T, ByVal value As T) As T
source = value
Return value
End Function
你不应该使用 .GetBuffer
方法对返回的MemoryStreams进行处理。.GetBuffer
返回底层数组,它通常大于Stream中的数据量。这就是为什么你在最后看到额外的0,以及为什么padding不能被正确读取。请看下面的备注部分 MemoryStream.GetBuffer方法的文档。
你应该做的是调用 outputStream.ToArray
它将返回一个Byte数组,只包含流中的相关数据,不包含所有尾部的0。