Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for saving public key to file using -output flag #318

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions cmd/tesla-keygen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func usage(w io.Writer) {
flag.PrintDefaults()
}

func printPublicKey(skey protocol.ECDHPrivateKey) bool {
func printPublicKey(skey protocol.ECDHPrivateKey, outputFile string) bool {
pkey := ecdsa.PublicKey{Curve: elliptic.P256()}
pkey.X, pkey.Y = elliptic.Unmarshal(elliptic.P256(), skey.PublicBytes())
if pkey.X == nil {
Expand All @@ -57,7 +57,20 @@ func printPublicKey(skey protocol.ECDHPrivateKey) bool {
if err != nil {
return false
}
pem.Encode(os.Stdout, &pem.Block{Type: "PUBLIC KEY", Bytes: derPublicKey})

// If outputFile is provided, write to file, else write to stdout
var out io.Writer = os.Stdout
if outputFile != "" {
file, err := os.Create(outputFile)
if err != nil {
writeErr("Failed to create output file: %s", err)
return false
}
defer file.Close()
out = file
}

pem.Encode(out, &pem.Block{Type: "PUBLIC KEY", Bytes: derPublicKey})
return true
}

Expand All @@ -77,9 +90,10 @@ func printPrivateKey(skey protocol.ECDHPrivateKey) error {
func main() {
// Command-line variables
var (
overwrite bool
skey protocol.ECDHPrivateKey
err error
overwrite bool
outputFile string
skey protocol.ECDHPrivateKey
err error
)
status := 1
defer func() {
Expand All @@ -90,7 +104,9 @@ func main() {
config.RegisterCommandLineFlags()
flag.Usage = cliUsage
flag.BoolVar(&overwrite, "f", false, "Overwrite existing key if it exists")
flag.StringVar(&outputFile, "output", "", "Path to save the public key")
flag.Parse()

if config.Debug {
log.SetLevel(log.LevelDebug)
}
Expand Down Expand Up @@ -130,7 +146,7 @@ func main() {
// Print key and exit if it already exists
skey, err = config.PrivateKey()
if err == nil {
if ok := printPublicKey(skey); !ok {
if ok := printPublicKey(skey, outputFile); !ok {
writeErr("Failed to parse key. The keyring may be corrupted. Run with -f to generate new key.")
return
}
Expand Down Expand Up @@ -164,7 +180,7 @@ func main() {
return
}

if ok := printPublicKey(skey); !ok {
if ok := printPublicKey(skey, outputFile); !ok {
writeErr("Failed to extract public key. Run with -f to generate new key pair.")
return
}
Expand Down