github.com/igggame/nebulas-go@v2.1.0+incompatible/crypto/crypto.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 crypto 20 21 import ( 22 "errors" 23 24 "github.com/nebulasio/go-nebulas/crypto/keystore" 25 "github.com/nebulasio/go-nebulas/crypto/keystore/secp256k1" 26 ) 27 28 var ( 29 // ErrAlgorithmInvalid invalid Algorithm for sign. 30 ErrAlgorithmInvalid = errors.New("invalid Algorithm") 31 ) 32 33 // NewPrivateKey generate a privatekey with Algorithm 34 func NewPrivateKey(alg keystore.Algorithm, data []byte) (keystore.PrivateKey, error) { 35 switch alg { 36 case keystore.SECP256K1: 37 var ( 38 priv *secp256k1.PrivateKey 39 err error 40 ) 41 if len(data) == 0 { 42 priv = secp256k1.GeneratePrivateKey() 43 } else { 44 priv = new(secp256k1.PrivateKey) 45 err = priv.Decode(data) 46 } 47 if err != nil { 48 return nil, err 49 } 50 return priv, nil 51 default: 52 return nil, ErrAlgorithmInvalid 53 } 54 } 55 56 // NewSignature returns a specific signature with the algorithm 57 func NewSignature(alg keystore.Algorithm) (keystore.Signature, error) { 58 switch alg { 59 case keystore.SECP256K1: 60 return new(secp256k1.Signature), nil 61 default: 62 return nil, ErrAlgorithmInvalid 63 } 64 } 65 66 // CheckAlgorithm check if support the input Algorithm 67 func CheckAlgorithm(alg keystore.Algorithm) error { 68 switch alg { 69 case keystore.SECP256K1: 70 return nil 71 default: 72 return ErrAlgorithmInvalid 73 } 74 }