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.

81 lines
1.9 KiB

  1. package babyjub
  2. import (
  3. "bytes"
  4. "crypto"
  5. "io"
  6. "math/big"
  7. )
  8. // BjjWrappedPublicKey is a wrapper for PublicKey.
  9. type BjjWrappedPublicKey struct {
  10. pubKey *PublicKey
  11. }
  12. // Equal returns true if the public keys are equal.
  13. func (pub *BjjWrappedPublicKey) Equal(x crypto.PublicKey) bool {
  14. var xk *BjjWrappedPublicKey
  15. switch x := x.(type) {
  16. case BjjWrappedPublicKey:
  17. xk = &x
  18. case *BjjWrappedPublicKey:
  19. xk = x
  20. default:
  21. return false
  22. }
  23. return pub.pubKey.X.Cmp(xk.pubKey.X) == 0 &&
  24. pub.pubKey.Y.Cmp(xk.pubKey.Y) == 0
  25. }
  26. // BjjWrappedPrivateKey is a wrapper for PrivateKey.
  27. type BjjWrappedPrivateKey struct {
  28. privKey *PrivateKey
  29. }
  30. // NewBjjWrappedKey creates a new BjjWrappedPrivateKey.
  31. func NewBjjWrappedKey(privKey *PrivateKey) *BjjWrappedPrivateKey {
  32. return &BjjWrappedPrivateKey{privKey}
  33. }
  34. // RandomBjjWrappedKey creates a new BjjWrappedPrivateKey with a random private key.
  35. func RandomBjjWrappedKey() *BjjWrappedPrivateKey {
  36. privKey := NewRandPrivKey()
  37. return NewBjjWrappedKey(&privKey)
  38. }
  39. // Public returns the public key of the private key.
  40. func (w *BjjWrappedPrivateKey) Public() crypto.PublicKey {
  41. return &BjjWrappedPublicKey{w.privKey.Public()}
  42. }
  43. // Sign signs the digest with the private key.
  44. func (w *BjjWrappedPrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
  45. hash := opts.HashFunc()
  46. switch hash {
  47. // alredy hashed
  48. case crypto.Hash(0):
  49. default:
  50. hasher := hash.New()
  51. hasher.Write(digest)
  52. digest = hasher.Sum(nil)
  53. }
  54. digestBI := big.NewInt(0).SetBytes(digest)
  55. sig := w.privKey.SignPoseidon(digestBI)
  56. return sig.Compress().MarshalText()
  57. }
  58. // Equal returns true if the private keys are equal.
  59. func (w *BjjWrappedPrivateKey) Equal(x crypto.PrivateKey) bool {
  60. var xk *BjjWrappedPrivateKey
  61. switch x := x.(type) {
  62. case BjjWrappedPrivateKey:
  63. xk = &x
  64. case *BjjWrappedPrivateKey:
  65. xk = x
  66. default:
  67. return false
  68. }
  69. return bytes.Equal(w.privKey[:], xk.privKey[:])
  70. }