You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcurve.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package brainpool
  2. import (
  3. "crypto/elliptic"
  4. "math/big"
  5. )
  6. var _ elliptic.Curve = (*rcurve)(nil)
  7. type rcurve struct {
  8. twisted elliptic.Curve
  9. params *elliptic.CurveParams
  10. z *big.Int
  11. zinv *big.Int
  12. z2 *big.Int
  13. z3 *big.Int
  14. zinv2 *big.Int
  15. zinv3 *big.Int
  16. }
  17. var (
  18. two = big.NewInt(2)
  19. three = big.NewInt(3)
  20. )
  21. func newrcurve(twisted elliptic.Curve, params *elliptic.CurveParams, z *big.Int) *rcurve {
  22. zinv := new(big.Int).ModInverse(z, params.P)
  23. return &rcurve{
  24. twisted: twisted,
  25. params: params,
  26. z: z,
  27. zinv: zinv,
  28. z2: new(big.Int).Exp(z, two, params.P),
  29. z3: new(big.Int).Exp(z, three, params.P),
  30. zinv2: new(big.Int).Exp(zinv, two, params.P),
  31. zinv3: new(big.Int).Exp(zinv, three, params.P),
  32. }
  33. }
  34. func (curve *rcurve) toTwisted(x, y *big.Int) (*big.Int, *big.Int) {
  35. var tx, ty big.Int
  36. tx.Mul(x, curve.z2)
  37. tx.Mod(&tx, curve.params.P)
  38. ty.Mul(y, curve.z3)
  39. ty.Mod(&ty, curve.params.P)
  40. return &tx, &ty
  41. }
  42. func (curve *rcurve) fromTwisted(tx, ty *big.Int) (*big.Int, *big.Int) {
  43. var x, y big.Int
  44. x.Mul(tx, curve.zinv2)
  45. x.Mod(&x, curve.params.P)
  46. y.Mul(ty, curve.zinv3)
  47. y.Mod(&y, curve.params.P)
  48. return &x, &y
  49. }
  50. func (curve *rcurve) Params() *elliptic.CurveParams {
  51. return curve.params
  52. }
  53. func (curve *rcurve) IsOnCurve(x, y *big.Int) bool {
  54. return curve.twisted.IsOnCurve(curve.toTwisted(x, y))
  55. }
  56. func (curve *rcurve) Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int) {
  57. tx1, ty1 := curve.toTwisted(x1, y1)
  58. tx2, ty2 := curve.toTwisted(x2, y2)
  59. return curve.fromTwisted(curve.twisted.Add(tx1, ty1, tx2, ty2))
  60. }
  61. func (curve *rcurve) Double(x1, y1 *big.Int) (x, y *big.Int) {
  62. return curve.fromTwisted(curve.twisted.Double(curve.toTwisted(x1, y1)))
  63. }
  64. func (curve *rcurve) ScalarMult(x1, y1 *big.Int, scalar []byte) (x, y *big.Int) {
  65. tx1, ty1 := curve.toTwisted(x1, y1)
  66. return curve.fromTwisted(curve.twisted.ScalarMult(tx1, ty1, scalar))
  67. }
  68. func (curve *rcurve) ScalarBaseMult(scalar []byte) (x, y *big.Int) {
  69. return curve.fromTwisted(curve.twisted.ScalarBaseMult(scalar))
  70. }