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.2 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Security.Cryptography;
  3. namespace Shadowsocks.Crypto
  4. {
  5. public static class RNG
  6. {
  7. private static RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
  8. public static void Reload()
  9. {
  10. _rng.Dispose();
  11. _rng = new RNGCryptoServiceProvider();
  12. }
  13. public static void GetSpan(Span<byte> span)
  14. {
  15. _rng.GetBytes(span);
  16. }
  17. public static Span<byte> GetSpan(int length)
  18. {
  19. Span<byte> span = new byte[length];
  20. _rng.GetBytes(span);
  21. return span;
  22. }
  23. public static byte[] GetBytes(int length)
  24. {
  25. byte[] buf = new byte[length];
  26. _rng.GetBytes(buf);
  27. return buf;
  28. }
  29. public static void GetBytes(byte[] buf, int len)
  30. {
  31. try
  32. {
  33. _rng.GetBytes(buf, 0, len);
  34. }
  35. catch
  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. }