Skip to content

Commit

Permalink
cmd/dkim-keygen: split into functions
Browse files Browse the repository at this point in the history
  • Loading branch information
emersion committed Feb 2, 2024
1 parent 39aad47 commit 833aecb
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion cmd/dkim-keygen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,17 @@ func init() {
flag.Parse()
}

type privateKey interface {
Public() crypto.PublicKey
}

func main() {
privKey := genPrivKey()
writePrivKey(privKey)
printPubKey(privKey.Public())
}

func genPrivKey() privateKey {
var (
privKey crypto.Signer
err error
Expand All @@ -46,7 +56,10 @@ func main() {
if err != nil {
log.Fatalf("Failed to generate key: %v", err)
}
return privKey
}

func writePrivKey(privKey privateKey) {
privBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
if err != nil {
log.Fatalf("Failed to marshal private key: %v", err)
Expand All @@ -69,16 +82,19 @@ func main() {
log.Fatalf("Failed to close key file: %v", err)
}
log.Printf("Private key written to %q", filename)
}

func printPubKey(pubKey crypto.PublicKey) {
var pubBytes []byte
switch pubKey := privKey.Public().(type) {
switch pubKey := pubKey.(type) {
case *rsa.PublicKey:
// RFC 6376 is inconsistent about whether RSA public keys should
// be formatted as RSAPublicKey or SubjectPublicKeyInfo.
// Erratum 3017 (https://www.rfc-editor.org/errata/eid3017)
// proposes allowing both. We use SubjectPublicKeyInfo for
// consistency with other implementations including opendkim,
// Gmail, and Fastmail.
var err error
pubBytes, err = x509.MarshalPKIXPublicKey(pubKey)
if err != nil {
log.Fatalf("Failed to marshal public key: %v", err)
Expand Down

0 comments on commit 833aecb

Please sign in to comment.