github.com/igggame/nebulas-go@v2.1.0+incompatible/crypto/keystore/secp256k1/privatekey.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 "github.com/nebulasio/go-nebulas/crypto/keystore" 23 "github.com/nebulasio/go-nebulas/crypto/utils" 24 "github.com/nebulasio/go-nebulas/util/logging" 25 "github.com/sirupsen/logrus" 26 ) 27 28 // PrivateKey ecdsa privatekey 29 type PrivateKey struct { 30 seckey []byte 31 } 32 33 // GeneratePrivateKey generate a new private key 34 func GeneratePrivateKey() *PrivateKey { 35 priv := new(PrivateKey) 36 seckey := NewSeckey() 37 priv.seckey = seckey 38 return priv 39 } 40 41 // Algorithm algorithm name 42 func (k *PrivateKey) Algorithm() keystore.Algorithm { 43 return keystore.SECP256K1 44 } 45 46 // Encoded encoded to byte 47 func (k *PrivateKey) Encoded() ([]byte, error) { 48 return k.seckey, nil 49 } 50 51 // Decode decode data to key 52 func (k *PrivateKey) Decode(data []byte) error { 53 if SeckeyVerify(data) == false { 54 return ErrInvalidPrivateKey 55 } 56 k.seckey = data 57 return nil 58 } 59 60 // Clear clear key content 61 func (k *PrivateKey) Clear() { 62 utils.ZeroBytes(k.seckey) 63 } 64 65 // PublicKey returns publickey 66 func (k *PrivateKey) PublicKey() keystore.PublicKey { 67 pub, err := GetPublicKey(k.seckey) 68 if err != nil { 69 logging.VLog().WithFields(logrus.Fields{ 70 "err": err, 71 }).Error("Failed to get public key.") 72 return nil 73 } 74 return NewPublicKey(pub) 75 } 76 77 // Sign sign hash with privatekey 78 func (k *PrivateKey) Sign(hash []byte) ([]byte, error) { 79 return Sign(hash, k.seckey) 80 }