1

I'm working with RSACryptoServiceProvider and I looked at examples on some book and on the Internet. In all the examples, a new instance of the type is being created in every method it is being used.

Is it not recommended to create only one RSACryptoServiceProvider instance and reuse it in all methods?

nulltoken
  • 64,429
  • 20
  • 138
  • 130
timyrik20
  • 77
  • 2
  • 5

1 Answers1

0

No - create your own each time, otherwise, once you start using different keys everything is going to go horribly wrong, or if you try to iterate through and need to decrypt something else. Furthermore it has thread safety problems.

Carsten Führmann
  • 3,119
  • 4
  • 26
  • 24
blowdart
  • 55,577
  • 12
  • 114
  • 149
  • Explain more? Well, if you reused the crypto provider and it's accessed by two threads at once you're going to get incorrect results back. It's not as if it takes major time to initialise anyway, so why run the risk of premature optimisation like this. – blowdart Jan 07 '12 at 15:08
  • That's the most obvious problem point - however you can't guarantee anything. Let's turn this around - why do you only want to create it once? It's a cheap object to create. – blowdart Jan 07 '12 at 19:20
  • I was just wondering! Now I understood why it was not necessary to do it) – timyrik20 Jan 07 '12 at 19:56