BigIntegerHelper.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Numerics;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Helper
  8. {
  9. public static class BigIntegerHelper
  10. {
  11. public static BigInteger RandBigInteger(int byteNum)
  12. {
  13. var bigIntegerBytes = new byte[byteNum];
  14. var random = new Random();
  15. random.NextBytes(bigIntegerBytes);
  16. var bigInteger = new BigInteger(bigIntegerBytes);
  17. return bigInteger;
  18. }
  19. public static BigInteger RandUnsignedBigInteger(int byteNum)
  20. {
  21. var bigIntegerBytes = new byte[byteNum];
  22. var random = new Random();
  23. random.NextBytes(bigIntegerBytes);
  24. return bigIntegerBytes.ToUBigInteger();
  25. }
  26. public static BigInteger ToBigInteger(this byte[] bytes)
  27. {
  28. return new BigInteger(bytes);
  29. }
  30. public static BigInteger ToUBigInteger(this byte[] bytes)
  31. {
  32. var dst = new byte[bytes.Length + 1];
  33. Array.Copy(bytes, dst, bytes.Length);
  34. return new BigInteger(dst);
  35. }
  36. public static byte[] ToUBigIntegerArray(this BigInteger bigInteger)
  37. {
  38. var result = bigInteger.ToByteArray();
  39. if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
  40. {
  41. Array.Resize(ref result, result.Length - 1);
  42. }
  43. return result;
  44. }
  45. }
  46. }