views:

165

answers:

1

Lets say we have this code that runs in the constructor:

    Dim initVectorBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(initVector)
    Dim saltValueBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(saltValue)

    Dim passPharse As String = GenerateKeyString(EncryptionKey)

    Dim password As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(passPharse, saltValueBytes, passwordIterations)

    Dim keyBytes As Byte() = password.GetBytes(CInt(keySize / 8))

    mSymmetricKey = New RijndaelManaged()
    mSymmetricKey.Padding = PaddingMode.PKCS7

    mSymmetricKey.Mode = CipherMode.CBC
    mSymmetricKey.BlockSize = 128

    mSymmetricKey.Key = keyBytes
    mSymmetricKey.IV = initVectorBytes

    mDecryptor = mSymmetricKey.CreateDecryptor()
    mEncryptor = mSymmetricKey.CreateEncryptor()

and then 2 public functions:

Public Function Encrypt(ByVal plainText As String) As String
    Dim plainTextBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(plainText)
    Dim cipherTextBytes As Byte() = mEncryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length)

    Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)

    Return cipherText
End Function
Public Function Decrypt(ByVal cipherText As String) As String
    Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)

    Dim plainTextBytes As Byte() = mDecryptor.TransformFinalBlock(cipherTextBytes, 0, cipherTextBytes.Length)

    Dim plainText As String = System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, plainTextBytes.Length)

    Return plainText
End Function

Would it be threadsafe to call those from more than one thread?

+1  A: 

According to the documentation it is not thread safe. You will have RijndaelManagedTransform instances in the mDecryptor and mEncryptor variables. TransformFinalBlock is an instance method which according to MSDN is not thread safe:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

If you want to be guaranteed to have a thread safe code you might need to synchronize the call to TransformFinalBlock method.

Darin Dimitrov
thanks i hoped that i had missed some thing, i guess ill just use [ThreadStatic] to solve the problem...
Petoj