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.

69 lines
1.6 KiB

  1. package signature
  2. import (
  3. "crypto/ecdsa"
  4. hex "encoding/hex"
  5. "errors"
  6. crypto "github.com/ethereum/go-ethereum/crypto"
  7. )
  8. type SignKeys struct {
  9. Public *ecdsa.PublicKey
  10. Private *ecdsa.PrivateKey
  11. }
  12. // generate new keys
  13. func (k *SignKeys) Generate() error {
  14. var err error
  15. key, err := crypto.GenerateKey()
  16. if err != nil {
  17. return err
  18. }
  19. k.Public = &key.PublicKey
  20. k.Private = key
  21. return nil
  22. }
  23. // imports a private hex key
  24. func (k *SignKeys) AddHexKey(privHex string) error {
  25. var err error
  26. k.Private, err = crypto.HexToECDSA(privHex)
  27. if err == nil {
  28. k.Public = &k.Private.PublicKey
  29. }
  30. return err
  31. }
  32. // returns the public and private keys as hex strings
  33. func (k *SignKeys) HexString() (string, string) {
  34. pubHex := hex.EncodeToString(crypto.CompressPubkey(k.Public))
  35. privHex := hex.EncodeToString(crypto.FromECDSA(k.Private))
  36. return pubHex, privHex
  37. }
  38. // message is a normal string (no HexString)
  39. func (k *SignKeys) Sign(message string) (string, error) {
  40. if k.Private == nil {
  41. return "", errors.New("No private key available")
  42. }
  43. hash := crypto.Keccak256([]byte(message))
  44. signature, err := crypto.Sign(hash, k.Private)
  45. signHex := hex.EncodeToString(signature)
  46. return signHex, err
  47. }
  48. // message is a normal string, signature and pubHex are HexStrings
  49. func (k *SignKeys) Verify(message, signHex, pubHex string) (bool, error) {
  50. signature, err := hex.DecodeString(signHex)
  51. if err != nil {
  52. return false, err
  53. }
  54. pub, err := hex.DecodeString(pubHex)
  55. if err != nil {
  56. return false, err
  57. }
  58. hash := crypto.Keccak256([]byte(message))
  59. result := crypto.VerifySignature(pub, hash, signature[:64])
  60. return result, nil
  61. }