You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Security.Cryptography;
  3. namespace Shadowsocks.Encryption
  4. {
  5. public static class RNG
  6. {
  7. private static RNGCryptoServiceProvider _rng = null;
  8. public static void Init()
  9. {
  10. if (_rng == null)
  11. _rng = new RNGCryptoServiceProvider();
  12. }
  13. public static void Close()
  14. {
  15. if (_rng == null) return;
  16. _rng.Dispose();
  17. _rng = null;
  18. }
  19. public static void Reload()
  20. {
  21. Close();
  22. Init();
  23. }
  24. public static void GetBytes(byte[] buf)
  25. {
  26. GetBytes(buf, buf.Length);
  27. }
  28. public static void GetBytes(byte[] buf, int len)
  29. {
  30. if (_rng == null) Reload();
  31. try
  32. {
  33. _rng.GetBytes(buf, 0, len);
  34. }
  35. catch (System.Exception)
  36. {
  37. // the backup way
  38. byte[] tmp = new byte[len];
  39. _rng.GetBytes(tmp);
  40. Buffer.BlockCopy(tmp, 0, buf, 0, len);
  41. }
  42. }
  43. }
  44. }