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.

84 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, err := w.privKey.SignPoseidon(digestBI)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return sig.Compress().MarshalText()
  60. }
  61. // Equal returns true if the private keys are equal.
  62. func (w *BjjWrappedPrivateKey) Equal(x crypto.PrivateKey) bool {
  63. var xk *BjjWrappedPrivateKey
  64. switch x := x.(type) {
  65. case BjjWrappedPrivateKey:
  66. xk = &x
  67. case *BjjWrappedPrivateKey:
  68. xk = x
  69. default:
  70. return false
  71. }
  72. return bytes.Equal(w.privKey[:], xk.privKey[:])
  73. }