Skip to content

Instantly share code, notes, and snippets.

@elvuel
Forked from rorycl/ed25519genandsave.go
Created August 8, 2023 14:07
Show Gist options
  • Save elvuel/4edc3291880fa91891366a08b84e06f5 to your computer and use it in GitHub Desktop.
Save elvuel/4edc3291880fa91891366a08b84e06f5 to your computer and use it in GitHub Desktop.
Generate ed25519 keys in PEM format using Go
// RCL 05 June 2021
/*
verify with `openssl pkey -in <privatekey>` or `openssl pkey -in <privatekey> -pubout`
the latter should match the publickey
*/
package main
import (
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"fmt"
"os"
)
// GenerateSaveEd25519 generates and saves ed25519 keys to disk after
// encoding into PEM format
func GenerateSaveEd25519(fb string) error {
var (
err error
b []byte
block *pem.Block
pub ed25519.PublicKey
priv ed25519.PrivateKey
)
pub, priv, err = ed25519.GenerateKey(rand.Reader)
if err != nil {
fmt.Printf("Generation error : %s", err)
os.Exit(1)
}
b, err = x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return err
}
block = &pem.Block{
Type: "PRIVATE KEY",
Bytes: b,
}
err = ioutil.WriteFile(fb, pem.EncodeToMemory(block), 0600)
if err != nil {
return err
}
// public key
b, err = x509.MarshalPKIXPublicKey(pub)
if err != nil {
return err
}
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: b,
}
fileName := fb + ".pub"
err = ioutil.WriteFile(fileName, pem.EncodeToMemory(block), 0644)
return err
}
func main() {
if len(os.Args) != 2 || os.Args[1] == "-h" || os.Args[1] == "--help" {
fmt.Printf("%s : generate pem formatted ed25519 keys\n", os.Args[0])
fmt.Println(" provide a single argument for the private key name")
fmt.Println(" the public key name will have '.pub' appended")
os.Exit(1)
}
FileBaseName := os.Args[1]
if err := GenerateSaveEd25519(FileBaseName); err != nil {
fmt.Printf("Error : %s\n", err)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment