github.com/igggame/nebulas-go@v2.1.0+incompatible/crypto/keystore/secp256k1/signature.go (about) 1 // Copyright (C) 2017 go-nebulas authors 2 // 3 // This file is part of the go-nebulas library. 4 // 5 // the go-nebulas library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // the go-nebulas library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 19 package secp256k1 20 21 import ( 22 "errors" 23 24 "github.com/nebulasio/go-nebulas/crypto/keystore" 25 ) 26 27 // Signature signature ecdsa 28 type Signature struct { 29 privateKey *PrivateKey 30 31 publicKey *PublicKey 32 } 33 34 // Algorithm secp256k1 algorithm 35 func (s *Signature) Algorithm() keystore.Algorithm { 36 return keystore.SECP256K1 37 } 38 39 // InitSign ecdsa init sign 40 func (s *Signature) InitSign(priv keystore.PrivateKey) error { 41 s.privateKey = priv.(*PrivateKey) 42 return nil 43 } 44 45 // Sign ecdsa sign 46 func (s *Signature) Sign(data []byte) (out []byte, err error) { 47 if s.privateKey == nil { 48 return nil, errors.New("please get private key first") 49 } 50 signature, err := s.privateKey.Sign(data) 51 if err != nil { 52 return nil, err 53 } 54 return signature, nil 55 } 56 57 // RecoverPublic returns a public key 58 func (s *Signature) RecoverPublic(data []byte, signature []byte) (keystore.PublicKey, error) { 59 pub, err := RecoverECDSAPublicKey(data, signature) 60 if err != nil { 61 return nil, err 62 } 63 s.publicKey = NewPublicKey(pub) 64 return s.publicKey, nil 65 } 66 67 // InitVerify ecdsa verify init 68 func (s *Signature) InitVerify(pub keystore.PublicKey) error { 69 s.publicKey = pub.(*PublicKey) 70 return nil 71 } 72 73 // Verify ecdsa verify 74 func (s *Signature) Verify(data []byte, signature []byte) (bool, error) { 75 if s.publicKey == nil { 76 return false, errors.New("please give public key first") 77 } 78 return s.publicKey.Verify(data, signature) 79 }