Luis Jasso
Luis Jasso

Reputation: 3

call Dispose() function after FlushFinalBlock()?

I have the following code:

Public Shared Function Crypt(text As String) As String
    If text <> "" Then
        Dim cryptoProvider As New DESCryptoServiceProvider()
        Dim ms As New MemoryStream()
        Dim cs As New CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_64, IV_64), CryptoStreamMode.Write)
        Dim sw As New StreamWriter(cs)

           sw.Write(text)
           sw.Flush()
           cs.FlushFinalBlock()
           ms.Flush()

        'convert back to a string
        Return Convert.ToBase64String(ms.GetBuffer(), 0, CInt(ms.Length))
    End If

    Return ""

End Function

after a Fortify scan, they report that i need to release the cs CryptoStream object.

As far as i know, FlushFinalBlock() method do it this job.

Do I need call the disponse() function too? Or may be is a false-positive issue?

Upvotes: 0

Views: 115

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54427

Any object that implements the IDisposable interface and is only used within the scope of a single block should be created with a Using statement. That way, it is guaranteed to be implicitly disposed at the end of the Using block. That applies even if a Return statement is hit or an exception is thrown. In your case, you are creating four disposable objects. There's no code required between the creation of each object or the destruction of each object so you don't need multiple nested Using blocks. You should use a single Using statement for them all:

Using cryptoProvider As New DESCryptoServiceProvider(),
      ms As New MemoryStream(),
      cs As New CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_64, IV_64), CryptoStreamMode.Write),
      sw As New StreamWriter(cs)
    '...
End Using

Upvotes: 1

Related Questions