gitea

Development moved to Codeberg

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
  79. 79
  80. 80
  81. 81
  82. 82
  83. 83
package brainpool

import (
	"crypto/elliptic"
	"math/big"
)

var _ elliptic.Curve = (*rcurve)(nil)

type rcurve struct {
	twisted elliptic.Curve
	params  *elliptic.CurveParams
	z       *big.Int
	zinv    *big.Int
	z2      *big.Int
	z3      *big.Int
	zinv2   *big.Int
	zinv3   *big.Int
}

var (
	two   = big.NewInt(2)
	three = big.NewInt(3)
)

func newrcurve(twisted elliptic.Curve, params *elliptic.CurveParams, z *big.Int) *rcurve {
	zinv := new(big.Int).ModInverse(z, params.P)
	return &rcurve{
		twisted: twisted,
		params:  params,
		z:       z,
		zinv:    zinv,
		z2:      new(big.Int).Exp(z, two, params.P),
		z3:      new(big.Int).Exp(z, three, params.P),
		zinv2:   new(big.Int).Exp(zinv, two, params.P),
		zinv3:   new(big.Int).Exp(zinv, three, params.P),
	}
}

func (curve *rcurve) toTwisted(x, y *big.Int) (*big.Int, *big.Int) {
	var tx, ty big.Int
	tx.Mul(x, curve.z2)
	tx.Mod(&tx, curve.params.P)
	ty.Mul(y, curve.z3)
	ty.Mod(&ty, curve.params.P)
	return &tx, &ty
}

func (curve *rcurve) fromTwisted(tx, ty *big.Int) (*big.Int, *big.Int) {
	var x, y big.Int
	x.Mul(tx, curve.zinv2)
	x.Mod(&x, curve.params.P)
	y.Mul(ty, curve.zinv3)
	y.Mod(&y, curve.params.P)
	return &x, &y
}

func (curve *rcurve) Params() *elliptic.CurveParams {
	return curve.params
}

func (curve *rcurve) IsOnCurve(x, y *big.Int) bool {
	return curve.twisted.IsOnCurve(curve.toTwisted(x, y))
}

func (curve *rcurve) Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int) {
	tx1, ty1 := curve.toTwisted(x1, y1)
	tx2, ty2 := curve.toTwisted(x2, y2)
	return curve.fromTwisted(curve.twisted.Add(tx1, ty1, tx2, ty2))
}

func (curve *rcurve) Double(x1, y1 *big.Int) (x, y *big.Int) {
	return curve.fromTwisted(curve.twisted.Double(curve.toTwisted(x1, y1)))
}

func (curve *rcurve) ScalarMult(x1, y1 *big.Int, scalar []byte) (x, y *big.Int) {
	tx1, ty1 := curve.toTwisted(x1, y1)
	return curve.fromTwisted(curve.twisted.ScalarMult(tx1, ty1, scalar))
}

func (curve *rcurve) ScalarBaseMult(scalar []byte) (x, y *big.Int) {
	return curve.fromTwisted(curve.twisted.ScalarBaseMult(scalar))
}