-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
66 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
autotls | ||
p2p-forge-certs/ | ||
identity.key |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package main | ||
|
||
// Borrowed from https://github.com/libp2p/go-libp2p-relay-daemon/blob/master/identity.go | ||
|
||
import ( | ||
"os" | ||
|
||
"github.com/libp2p/go-libp2p/core/crypto" | ||
) | ||
|
||
// LoadIdentity reads a private key from the given path and, if it does not | ||
// exist, generates a new one. | ||
func LoadIdentity(keyPath string) (crypto.PrivKey, error) { | ||
if _, err := os.Stat(keyPath); err == nil { | ||
return ReadIdentity(keyPath) | ||
} else if os.IsNotExist(err) { | ||
logger.Infof("Generating peer identity in %s\n", keyPath) | ||
return GenerateIdentity(keyPath) | ||
} else { | ||
return nil, err | ||
} | ||
} | ||
|
||
// ReadIdentity reads a private key from the given path. | ||
func ReadIdentity(path string) (crypto.PrivKey, error) { | ||
bytes, err := os.ReadFile(path) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return crypto.UnmarshalPrivateKey(bytes) | ||
} | ||
|
||
// GenerateIdentity writes a new random private key to the given path. | ||
func GenerateIdentity(path string) (crypto.PrivKey, error) { | ||
privk, _, err := crypto.GenerateKeyPair(crypto.Ed25519, 0) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
bytes, err := crypto.MarshalPrivateKey(privk) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
err = os.WriteFile(path, bytes, 0400) | ||
|
||
return privk, err | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters