Created
April 28, 2025 06:57
-
-
Save dboyliao/346d51b7b448ba031539771d6ab7e6f3 to your computer and use it in GitHub Desktop.
Generate Ed25519 key pair in PEM format
This file contains hidden or 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
package main | |
import ( | |
"crypto/ed25519" | |
"crypto/rand" | |
"crypto/x509" | |
"encoding/pem" | |
"fmt" | |
"os" | |
) | |
func main() { | |
// Generate ED25519 key pair | |
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Error generating ED25519 key pair: %v\n", err) | |
os.Exit(1) | |
} | |
// Convert private key to PKCS8 form | |
privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Error marshaling private key: %v\n", err) | |
os.Exit(1) | |
} | |
// Create PEM block for private key | |
privateKeyPEM := &pem.Block{ | |
Type: "PRIVATE KEY", | |
Bytes: privateKeyBytes, | |
} | |
// Convert public key to PKIX form | |
publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Error marshaling public key: %v\n", err) | |
os.Exit(1) | |
} | |
// Create PEM block for public key | |
publicKeyPEM := &pem.Block{ | |
Type: "PUBLIC KEY", | |
Bytes: publicKeyBytes, | |
} | |
os.WriteFile("public_key.pem", pem.EncodeToMemory(publicKeyPEM), 0644) | |
os.WriteFile("private_key.pem", pem.EncodeToMemory(privateKeyPEM), 0644) | |
// Print both keys | |
fmt.Println("ED25519 Private Key (PEM format):") | |
fmt.Println(string(pem.EncodeToMemory(privateKeyPEM))) | |
fmt.Println("ED25519 Public Key (PEM format):") | |
fmt.Println(string(pem.EncodeToMemory(publicKeyPEM))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment