ECDsaSigner.cs 8.1 KB

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