BigIntegerHelper.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Numerics;
  3. namespace Helper
  4. {
  5. public static class BigIntegerHelper
  6. {
  7. public static BigInteger RandBigInteger(int byteNum)
  8. {
  9. var bigIntegerBytes = new byte[byteNum];
  10. var random = new Random();
  11. random.NextBytes(bigIntegerBytes);
  12. var bigInteger = new BigInteger(bigIntegerBytes);
  13. return bigInteger;
  14. }
  15. public static BigInteger RandUnsignedBigInteger(int byteNum)
  16. {
  17. var bigIntegerBytes = new byte[byteNum];
  18. var random = new Random();
  19. random.NextBytes(bigIntegerBytes);
  20. //bigIntegerBytes = "C5487A2909326D52A615C07ADFECB55FCD0771".HexToBytes().Reverse();
  21. return bigIntegerBytes.ToUBigInteger();
  22. }
  23. public static BigInteger ToBigInteger(this byte[] bytes)
  24. {
  25. return new BigInteger(bytes);
  26. }
  27. public static BigInteger ToUBigInteger(this byte[] bytes)
  28. {
  29. var dst = new byte[bytes.Length + 1];
  30. Array.Copy(bytes, dst, bytes.Length);
  31. return new BigInteger(dst);
  32. }
  33. public static byte[] ToUBigIntegerArray(this BigInteger bigInteger)
  34. {
  35. var result = bigInteger.ToByteArray();
  36. if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
  37. {
  38. Array.Resize(ref result, result.Length - 1);
  39. }
  40. return result;
  41. }
  42. /// <summary>
  43. /// 返回非负值
  44. /// </summary>
  45. /// <param name="value"></param>
  46. /// <param name="exponent"></param>
  47. /// <param name="modulus"></param>
  48. /// <returns></returns>
  49. public static BigInteger UModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
  50. {
  51. BigInteger result = BigInteger.ModPow(value, exponent, modulus);
  52. if (result < 0)
  53. {
  54. result += modulus;
  55. }
  56. return result;
  57. }
  58. }
  59. }