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.

104 lines
1.9 KiB

  1. package core
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/elliptic"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "errors"
  8. "math/big"
  9. )
  10. // Address is the type data for addresses
  11. type Address [32]byte
  12. func (addr Address) String() string {
  13. return hex.EncodeToString(addr[:])
  14. }
  15. func NewKey() (*ecdsa.PrivateKey, error) {
  16. curve := elliptic.P256()
  17. // privatekey := new(ecdsa.PrivateKey)
  18. privatekey, err := ecdsa.GenerateKey(curve, rand.Reader)
  19. if err != nil {
  20. return nil, err
  21. }
  22. return privatekey, err
  23. }
  24. func PackPubK(pubK *ecdsa.PublicKey) []byte {
  25. return elliptic.Marshal(pubK.Curve, pubK.X, pubK.Y)
  26. }
  27. func UnpackPubK(b []byte) *ecdsa.PublicKey {
  28. x, y := elliptic.Unmarshal(elliptic.P256(), b)
  29. return &ecdsa.PublicKey{
  30. Curve: elliptic.P256(),
  31. X: x,
  32. Y: y,
  33. }
  34. }
  35. func AddressFromPrivK(privK *ecdsa.PrivateKey) Address {
  36. h := HashBytes(PackPubK(&privK.PublicKey))
  37. return Address(h)
  38. }
  39. func AddressFromPubK(pubK *ecdsa.PublicKey) Address {
  40. h := HashBytes(PackPubK(pubK))
  41. return Address(h)
  42. }
  43. func (sig *Signature) Bytes() []byte {
  44. b := sig.R.Bytes()
  45. b = append(b, sig.S.Bytes()...)
  46. return b
  47. }
  48. func SignatureFromBytes(b []byte) (*Signature, error) {
  49. if len(b) != 64 {
  50. return nil, errors.New("Invalid signature")
  51. }
  52. rBytes := b[:32]
  53. sBytes := b[32:]
  54. r := new(big.Int).SetBytes(rBytes)
  55. s := new(big.Int).SetBytes(sBytes)
  56. sig := &Signature{
  57. R: r,
  58. S: s,
  59. }
  60. return sig, nil
  61. }
  62. type Signature struct {
  63. R *big.Int
  64. S *big.Int
  65. }
  66. func Sign(privK *ecdsa.PrivateKey, m []byte) (*Signature, error) {
  67. // r := big.NewInt(0)
  68. // s := big.NewInt(0)
  69. hashMsg := HashBytes(m)
  70. r, s, err := ecdsa.Sign(rand.Reader, privK, hashMsg[:])
  71. if err != nil {
  72. return nil, err
  73. }
  74. sig := &Signature{
  75. R: r,
  76. S: s,
  77. }
  78. return sig, nil
  79. }
  80. func VerifySignature(pubK *ecdsa.PublicKey, m []byte, sig Signature) bool {
  81. hashMsg := HashBytes(m)
  82. verified := ecdsa.Verify(pubK, hashMsg[:], sig.R, sig.S)
  83. return verified
  84. }