github.com/igggame/nebulas-go@v2.1.0+incompatible/net/network_key.go (about) 1 // Copyright (C) 2018 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 net 20 21 import ( 22 "crypto/rand" 23 "encoding/base64" 24 "io/ioutil" 25 26 crypto "github.com/libp2p/go-libp2p-crypto" 27 ) 28 29 // LoadNetworkKeyFromFile load network priv key from file. 30 func LoadNetworkKeyFromFile(path string) (crypto.PrivKey, error) { 31 data, err := ioutil.ReadFile(path) 32 if err != nil { 33 return nil, err 34 } 35 return UnmarshalNetworkKey(string(data)) 36 } 37 38 // LoadNetworkKeyFromFileOrCreateNew load network priv key from file or create new one. 39 func LoadNetworkKeyFromFileOrCreateNew(path string) (crypto.PrivKey, error) { 40 if path == "" { 41 return GenerateEd25519Key() 42 } 43 return LoadNetworkKeyFromFile(path) 44 } 45 46 // UnmarshalNetworkKey unmarshal network key. 47 func UnmarshalNetworkKey(data string) (crypto.PrivKey, error) { 48 binaryData, err := base64.StdEncoding.DecodeString(data) 49 if err != nil { 50 return nil, err 51 } 52 53 return crypto.UnmarshalPrivateKey(binaryData) 54 } 55 56 // MarshalNetworkKey marshal network key. 57 func MarshalNetworkKey(key crypto.PrivKey) (string, error) { 58 binaryData, err := crypto.MarshalPrivateKey(key) 59 if err != nil { 60 return "", err 61 } 62 63 return base64.StdEncoding.EncodeToString(binaryData), nil 64 } 65 66 // GenerateEd25519Key return a new generated Ed22519 Private key. 67 func GenerateEd25519Key() (crypto.PrivKey, error) { 68 key, _, err := crypto.GenerateEd25519Key(rand.Reader) 69 return key, err 70 }