Archived Forum Post

Index of archived forum posts

Question:

Download encrypted file and zip on the fly

Jan 21 '14 at 15:53

Hello,

I have a small problem one of my code. It downloads files are encrypted on a server. The decryption is on the fly while the download run. If I save the data to a file it works good, but when I want to add the data to a zip entry it uses a lot of memory. Have somebody idea how to write it directly to the zip entry instead of the memory. This is my code:

zip.UnlockComponent(zip_ck_unlock)
zip.NewZip(path + ".zip")
zip.OverwriteExisting = False
For Each Node As Node In AdvTree1.Nodes
zip.AppendNew(Node.Cells(1).Text) 'This is the filename in the list
Dim entry As New Chilkat.ZipEntry()
    entry = zip.FirstMatchingEntry(Node.Cells(1).Text)
With crypt
    .UnlockComponent(crypt_ck_unlock)
    .SetEncodedKey("KEY", "ascii")
    .SetEncodedIV("IV", "ascii")
    .CryptAlgorithm = "aes"
    .CipherMode = "cbc"
    .KeyLength = 256
    .PaddingScheme = 0
    .EnableEvents = True
End With

size = Node.Cells(4).Text
Dim handle As String = sftp_dl.OpenFile(file_path, "readOnly", "openExisting")

Dim b As Byte() = New Byte(StreamBuffer) {} 'StreamBuffer is the size of the buffer
Dim decryptedChunk As Byte()
Dim idx As Integer
Dim numChunks As Integer = = Math.Floor(CType(size, Int64) / b.Length)

crypt.FirstChunk = True
crypt.LastChunk = False

For idx = 0 To numChunks
    b = sftp_dl.ReadFileBytes(handle, b.Length)
    If idx = numChunks Then
        crypt.LastChunk = True
        Dim lastBlock As Byte() = New Byte(b.Length - 1) {}
        Dim i As Integer
        For i = 0 To b.Length - 1
            lastBlock(i) = b(i)
        Next
        decryptedChunk = crypt.DecryptBytes(lastBlock)
    Else
        decryptedChunk = crypt.DecryptBytes(b)
    End If
    entry.AppendData(decryptedChunk)
    crypt.FirstChunk = False
Next
Next

Thank you for your help!