ECDsaSigner.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Math;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Security;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  10. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
  11. {
  12. /**
  13. * EC-DSA as described in X9.62
  14. */
  15. public class ECDsaSigner
  16. : IDsa
  17. {
  18. private static readonly BigInteger Eight = BigInteger.ValueOf(8);
  19. protected readonly IDsaKCalculator kCalculator;
  20. protected ECKeyParameters key = null;
  21. protected SecureRandom random = null;
  22. /**
  23. * Default configuration, random K values.
  24. */
  25. public ECDsaSigner()
  26. {
  27. this.kCalculator = new RandomDsaKCalculator();
  28. }
  29. /**
  30. * Configuration with an alternate, possibly deterministic calculator of K.
  31. *
  32. * @param kCalculator a K value calculator.
  33. */
  34. public ECDsaSigner(IDsaKCalculator kCalculator)
  35. {
  36. this.kCalculator = kCalculator;
  37. }
  38. public virtual string AlgorithmName
  39. {
  40. get { return "ECDSA"; }
  41. }
  42. public virtual void Init(bool forSigning, ICipherParameters parameters)
  43. {
  44. SecureRandom providedRandom = null;
  45. if (forSigning)
  46. {
  47. if (parameters is ParametersWithRandom)
  48. {
  49. ParametersWithRandom rParam = (ParametersWithRandom)parameters;
  50. providedRandom = rParam.Random;
  51. parameters = rParam.Parameters;
  52. }
  53. if (!(parameters is ECPrivateKeyParameters))
  54. throw new InvalidKeyException("EC private key required for signing");
  55. this.key = (ECPrivateKeyParameters)parameters;
  56. }
  57. else
  58. {
  59. if (!(parameters is ECPublicKeyParameters))
  60. throw new InvalidKeyException("EC public key required for verification");
  61. this.key = (ECPublicKeyParameters)parameters;
  62. }
  63. this.random = InitSecureRandom(forSigning && !kCalculator.IsDeterministic, providedRandom);
  64. }
  65. public virtual BigInteger Order
  66. {
  67. get { return key.Parameters.N; }
  68. }
  69. // 5.3 pg 28
  70. /**
  71. * Generate a signature for the given message using the key we were
  72. * initialised with. For conventional DSA the message should be a SHA-1
  73. * hash of the message of interest.
  74. *
  75. * @param message the message that will be verified later.
  76. */
  77. public virtual BigInteger[] GenerateSignature(byte[] message)
  78. {
  79. ECDomainParameters ec = key.Parameters;
  80. BigInteger n = ec.N;
  81. BigInteger e = CalculateE(n, message);
  82. BigInteger d = ((ECPrivateKeyParameters)key).D;
  83. if (kCalculator.IsDeterministic)
  84. {
  85. kCalculator.Init(n, d, message);
  86. }
  87. else
  88. {
  89. kCalculator.Init(n, random);
  90. }
  91. BigInteger r, s;
  92. ECMultiplier basePointMultiplier = CreateBasePointMultiplier();
  93. // 5.3.2
  94. do // Generate s
  95. {
  96. BigInteger k;
  97. do // Generate r
  98. {
  99. k = kCalculator.NextK();
  100. ECPoint p = basePointMultiplier.Multiply(ec.G, k).Normalize();
  101. // 5.3.3
  102. r = p.AffineXCoord.ToBigInteger().Mod(n);
  103. }
  104. while (r.SignValue == 0);
  105. s = BigIntegers.ModOddInverse(n, k).Multiply(e.Add(d.Multiply(r))).Mod(n);
  106. }
  107. while (s.SignValue == 0);
  108. return new BigInteger[]{ r, s };
  109. }
  110. // 5.4 pg 29
  111. /**
  112. * return true if the value r and s represent a DSA signature for
  113. * the passed in message (for standard DSA the message should be
  114. * a SHA-1 hash of the real message to be verified).
  115. */
  116. public virtual bool VerifySignature(byte[] message, BigInteger r, BigInteger s)
  117. {
  118. BigInteger n = key.Parameters.N;
  119. // r and s should both in the range [1,n-1]
  120. if (r.SignValue < 1 || s.SignValue < 1
  121. || r.CompareTo(n) >= 0 || s.CompareTo(n) >= 0)
  122. {
  123. return false;
  124. }
  125. BigInteger e = CalculateE(n, message);
  126. BigInteger c = BigIntegers.ModOddInverseVar(n, s);
  127. BigInteger u1 = e.Multiply(c).Mod(n);
  128. BigInteger u2 = r.Multiply(c).Mod(n);
  129. ECPoint G = key.Parameters.G;
  130. ECPoint Q = ((ECPublicKeyParameters) key).Q;
  131. ECPoint point = ECAlgorithms.SumOfTwoMultiplies(G, u1, Q, u2);
  132. if (point.IsInfinity)
  133. return false;
  134. /*
  135. * If possible, avoid normalizing the point (to save a modular inversion in the curve field).
  136. *
  137. * There are ~cofactor elements of the curve field that reduce (modulo the group order) to 'r'.
  138. * If the cofactor is known and small, we generate those possible field values and project each
  139. * of them to the same "denominator" (depending on the particular projective coordinates in use)
  140. * as the calculated point.X. If any of the projected values matches point.X, then we have:
  141. * (point.X / Denominator mod p) mod n == r
  142. * as required, and verification succeeds.
  143. *
  144. * Based on an original idea by Gregory Maxwell (https://github.com/gmaxwell), as implemented in
  145. * the libsecp256k1 project (https://github.com/bitcoin/secp256k1).
  146. */
  147. ECCurve curve = point.Curve;
  148. if (curve != null)
  149. {
  150. BigInteger cofactor = curve.Cofactor;
  151. if (cofactor != null && cofactor.CompareTo(Eight) <= 0)
  152. {
  153. ECFieldElement D = GetDenominator(curve.CoordinateSystem, point);
  154. if (D != null && !D.IsZero)
  155. {
  156. ECFieldElement X = point.XCoord;
  157. while (curve.IsValidFieldElement(r))
  158. {
  159. ECFieldElement R = curve.FromBigInteger(r).Multiply(D);
  160. if (R.Equals(X))
  161. {
  162. return true;
  163. }
  164. r = r.Add(n);
  165. }
  166. return false;
  167. }
  168. }
  169. }
  170. BigInteger v = point.Normalize().AffineXCoord.ToBigInteger().Mod(n);
  171. return v.Equals(r);
  172. }
  173. protected virtual BigInteger CalculateE(BigInteger n, byte[] message)
  174. {
  175. int messageBitLength = message.Length * 8;
  176. BigInteger trunc = new BigInteger(1, message);
  177. if (n.BitLength < messageBitLength)
  178. {
  179. trunc = trunc.ShiftRight(messageBitLength - n.BitLength);
  180. }
  181. return trunc;
  182. }
  183. protected virtual ECMultiplier CreateBasePointMultiplier()
  184. {
  185. return new FixedPointCombMultiplier();
  186. }
  187. protected virtual ECFieldElement GetDenominator(int coordinateSystem, ECPoint p)
  188. {
  189. switch (coordinateSystem)
  190. {
  191. case ECCurve.COORD_HOMOGENEOUS:
  192. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  193. case ECCurve.COORD_SKEWED:
  194. return p.GetZCoord(0);
  195. case ECCurve.COORD_JACOBIAN:
  196. case ECCurve.COORD_JACOBIAN_CHUDNOVSKY:
  197. case ECCurve.COORD_JACOBIAN_MODIFIED:
  198. return p.GetZCoord(0).Square();
  199. default:
  200. return null;
  201. }
  202. }
  203. protected virtual SecureRandom InitSecureRandom(bool needed, SecureRandom provided)
  204. {
  205. return !needed ? null : CryptoServicesRegistrar.GetSecureRandom(provided);
  206. }
  207. }
  208. }
  209. #pragma warning restore
  210. #endif