mirror of
https://github.com/DeBrosOfficial/network.git
synced 2025-10-06 04:49:08 +00:00

- Added encryption module identity.go for reusable identity create, save etc funtions - Updated make file to support identity/main.go - Updated node/node.go on loadOrCreateIdentity to use encryption.identity - Updated cli/main.go to remove fallbacks for identity - Updated install-debros-network.sh script to use new ./cmd/identity and fixed port order on print - Updated makefile and changelog
72 lines
1.3 KiB
Go
72 lines
1.3 KiB
Go
package encryption
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/libp2p/go-libp2p/core/crypto"
|
|
"github.com/libp2p/go-libp2p/core/peer"
|
|
)
|
|
|
|
type IdentityInfo struct {
|
|
PrivateKey crypto.PrivKey
|
|
PublicKey crypto.PubKey
|
|
PeerID peer.ID
|
|
}
|
|
|
|
func GenerateIdentity() (*IdentityInfo, error) {
|
|
priv, pub, err := crypto.GenerateKeyPairWithReader(crypto.Ed25519, 2048, rand.Reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
peerID, err := peer.IDFromPublicKey(pub)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &IdentityInfo{
|
|
PrivateKey: priv,
|
|
PublicKey: pub,
|
|
PeerID: peerID,
|
|
}, nil
|
|
}
|
|
|
|
func SaveIdentity(identity *IdentityInfo, path string) error {
|
|
data, err := crypto.MarshalPrivateKey(identity.PrivateKey)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
|
|
return err
|
|
}
|
|
|
|
return os.WriteFile(path, data, 0600)
|
|
}
|
|
|
|
func LoadIdentity(path string) (*IdentityInfo, error) {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
priv, err := crypto.UnmarshalPrivateKey(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
pub := priv.GetPublic()
|
|
peerID, err := peer.IDFromPublicKey(pub)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &IdentityInfo{
|
|
PrivateKey: priv,
|
|
PublicKey: pub,
|
|
PeerID: peerID,
|
|
}, nil
|
|
}
|