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.

RNG.cs 1.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. _rng = _rng ?? new RNGCryptoServiceProvider();
  11. }
  12. public static void Close()
  13. {
  14. _rng?.Dispose();
  15. _rng = null;
  16. }
  17. public static void Reload()
  18. {
  19. Close();
  20. Init();
  21. }
  22. public static void GetBytes(byte[] buf)
  23. {
  24. GetBytes(buf, buf.Length);
  25. }
  26. public static void GetBytes(byte[] buf, int len)
  27. {
  28. if (_rng == null) Init();
  29. try
  30. {
  31. _rng.GetBytes(buf, 0, len);
  32. }
  33. catch
  34. {
  35. // the backup way
  36. byte[] tmp = new byte[len];
  37. _rng.GetBytes(tmp);
  38. Buffer.BlockCopy(tmp, 0, buf, 0, len);
  39. }
  40. }
  41. }
  42. }