Thread Safety of .NET Encryption Classes?
One could solve the concurrency problem simply with a cache based on a concurrent stack:
static ConcurrentStack<ICryptoTransform> decryptors = new ConcurrentStack<ICryptoTransform>();
void Encrypt()
{
// Pop decryptor from cache...
ICryptoTransform decryptor;
if (!decryptors.TryPop(out decryptor))
{
// ... or create a new one since cache is depleted
AesManaged aes = new AesManaged();
aes.Key = key;
aes.IV = iv;
decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
}
try
{
//// use decryptor
}
finally
{
decryptors.Push(decryptor);
}
}
1) Yes.
2) One you dispose of it, you cannot use it. Up until then, you can share/use it (but see below)
3-4) From MSDN:
"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 keep this around, and share it between threads, you'll need to implement locking and treat it as a locked resource. Otherwise, I'd recommend just making separate versions as needed, and disposing of them when you're done.
5) I would recommend creating these as needed, and then trying to optimize it if later you find you have a performance problem. Don't worry about the performance implications of creating a new version until you see that's its a problem after profiling.