Created
June 5, 2021 16:14
-
-
Save rorycl/d300f3ab942fd79e6cc1f37db0c6260f to your computer and use it in GitHub Desktop.
Generate ed25519 keys in PEM format using Go
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
// 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