Hi @Peter Volz ,
To make the class Simple3Des disposable you need to implement the IDisposable interface and then add the Dispose method to the class to release the resource. Since both TripleDESCryptoServiceProvider and SHA1CryptoServiceProvider classes implement the IDisposable interface, you need to make sure to call their Dispose method at the appropriate time to release related resources.
Public NotInheritable Class Simple3Des
Implements IDisposable
Private TripleDes As New TripleDESCryptoServiceProvider
Private sha1 As New SHA1CryptoServiceProvider
Private disposed As Boolean = False
Private Function TruncateHash(ByVal key As String, ByVal length As Integer) As Byte()
Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key)
Dim hash() As Byte = sha1.ComputeHash(keyBytes)
ReDim Preserve hash(length - 1)
Return hash
End Function
Sub New(ByVal key As String)
TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8)
TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8)
End Sub
Public Function EncryptData(ByVal plaintext As String) As String
Dim plaintextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext)
Dim ms As New System.IO.MemoryStream
Dim encStream As New CryptoStream(ms, TripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
encStream.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray)
End Function
Public Function DecryptData(ByVal encryptedtext As String) As String
Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext)
Dim ms As New System.IO.MemoryStream
Dim decStream As New CryptoStream(ms, TripleDes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
decStream.FlushFinalBlock()
Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
End Function
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Sub Dispose(disposing As Boolean)
If Not disposed Then
If disposing Then
TripleDes.Dispose()
sha1.Dispose()
End If
disposed = True
End If
End Sub
Protected Overrides Sub Finalize()
Dispose(False)
MyBase.Finalize()
End Sub
End Class
Then you can use the Using statement to ensure the correct release of resources.
Best Regards.
Jiachen Li
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.