github.com/inklabsfoundation/inkchain@v0.17.1-0.20181025012015-c3cef8062f19/common/crypto/signature_cgo.go (about) 1 // Copyright 2017 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // +build !nacl,!js,!nocgo 18 19 package crypto 20 21 import ( 22 "crypto/ecdsa" 23 "crypto/elliptic" 24 "fmt" 25 "github.com/inklabsfoundation/inkchain/common/crypto/secp256k1" 26 ) 27 28 29 func Ecrecover(hash, sig []byte) ([]byte, error) { 30 return secp256k1.RecoverPubkey(hash, sig) 31 } 32 33 func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) { 34 s, err := Ecrecover(hash, sig) 35 if err != nil { 36 return nil, err 37 } 38 39 x, y := elliptic.Unmarshal(S256(), s) 40 return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil 41 } 42 43 // Sign calculates an ECDSA signature. 44 // 45 // This function is susceptible to chosen plaintext attacks that can leak 46 // information about the private key that is used for signing. Callers must 47 // be aware that the given hash cannot be chosen by an adversery. Common 48 // solution is to hash any input before calculating the signature. 49 // 50 // The produced signature is in the [R || S || V] format where V is 0 or 1. 51 func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) { 52 if len(hash) != 32 { 53 return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash)) 54 } 55 seckey := secp256k1.PaddedBigBytes(prv.D, prv.Params().BitSize/8) 56 defer zeroBytes(seckey) 57 return secp256k1.Sign(hash, seckey) 58 } 59 60 // S256 returns an instance of the secp256k1 curve. 61 func S256() elliptic.Curve { 62 return secp256k1.S256() 63 } 64 65 func zeroBytes(bytes []byte) { 66 for i := range bytes { 67 bytes[i] = 0 68 } 69 }