BigIntegerHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Numerics;
  3. namespace Common.Helper
  4. {
  5. public static class BigIntegerHelper
  6. {
  7. public static BigInteger RandBigInteger(int byteNum)
  8. {
  9. var bigIntegerBytes = new byte[byteNum];
  10. Random random = new Random();
  11. random.NextBytes(bigIntegerBytes);
  12. BigInteger bigInteger = new BigInteger(bigIntegerBytes);
  13. return bigInteger;
  14. }
  15. public static BigInteger RandUnsignedBigInteger(int byteNum)
  16. {
  17. var bigIntegerBytes = new byte[byteNum];
  18. Random random = new Random();
  19. random.NextBytes(bigIntegerBytes);
  20. //bigIntegerBytes = "C6DFEDA1EAAC7417A191EE5EC6062CE9546614".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. public static byte[] ToUBigIntegerArray(this BigInteger bigInteger, int length)
  43. {
  44. var result = bigInteger.ToByteArray();
  45. if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
  46. {
  47. Array.Resize(ref result, result.Length - 1);
  48. }
  49. if (length > result.Length)
  50. {
  51. Array.Resize(ref result, length);
  52. }
  53. return result;
  54. }
  55. /// <summary>
  56. /// 返回非负值
  57. /// </summary>
  58. /// <param name="value"></param>
  59. /// <param name="exponent"></param>
  60. /// <param name="modulus"></param>
  61. /// <returns></returns>
  62. public static BigInteger UModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
  63. {
  64. BigInteger result = BigInteger.ModPow(value, exponent, modulus);
  65. if (result < 0)
  66. {
  67. result += modulus;
  68. }
  69. return result;
  70. }
  71. }
  72. }