使用加密的 .Net Stream Pipeline



>我有一个工作的文件复制发射器,以及一个由于解压缩流"不可写"而失败的接收器。请问我如何正确编写接收器?

    Private Async Function SendFileCompressedEncryptedAsync(sourceFile As String, serverSocket As Socket, sa As SymmetricAlgorithm) As Task
    Dim trans As ICryptoTransform = sa.CreateEncryptor()    'create encryptor
    Try
        Using destinationStream As NetworkStream = New NetworkStream(serverSocket) 'requires connected socket
            'CryptoStream   p1: stream on which to perform crypto transform; p2: mode
            Using cryptStream As New CryptoStream(destinationStream, trans, CryptoStreamMode.Write)
                'CompressionStream  p1: stream on which to perform operation; p2: mode
                Using compressionStream As Compression.DeflateStream = New DeflateStream(cryptStream, CompressionMode.Compress)
                    Using sourceStream As FileStream = File.Open(sourceFile, FileMode.Open)
                        Await sourceStream.CopyToAsync(compressionStream)
                    End Using
                End Using
            End Using
        End Using
    Catch ex As Exception
        Console.WriteLine("Error sender: " & ex.ToString)
    End Try
End Function
Private Async Function ReceiveFileCompressedEncryptedAsync(clientSocket As Socket, destinationFile As String, sa As SymmetricAlgorithm) As Task
    Dim trans As ICryptoTransform = sa.CreateDecryptor()        'create decryptor
    Try
        Using destinationStream As FileStream = File.Create(destinationFile)
            Using sourceStream As New NetworkStream(clientSocket) 'requires connected socket
                'CompressionStream  p1: stream on which to perform operation; p2: mode
                Using decompressionStream As New DeflateStream(destinationStream, CompressionMode.Decompress)
                    'CryptoStream   p1: stream on which to perform crypto transform; p2: mode
                    Using decryptStream As New CryptoStream(decompressionStream, trans, CryptoStreamMode.Write)
                        Await sourceStream.CopyToAsync(decryptStream)
                    End Using
                End Using
            End Using
        End Using
    Catch ex As Exception
        Console.WriteLine("Error receiver: " & ex.ToString)
    End Try
End Function
似乎

DeflateStream只有在创建压缩到底层流时才可写。您正在尝试在打开它以解压缩流时写入它。那行不通。尝试以下操作(免责声明:我从未编写过 VB,因此尚未编译和运行(:

Using decryptStream As New CryptoStream(sourceStream, trans, CryptoStreamMode.Read)
    Using decompressionStream As New DeflateStream(destinationStream, CompressionMode.Decompress)
        Await decompressionStream.CopyToAsync(destinationStream)
    End Using
End Using

相关内容

  • 没有找到相关文章

最新更新