63 lines
1.5 KiB
Go
63 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"crypto/rand"
|
|
"crypto/x509"
|
|
"encoding/pem"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
func generateKeys(yamlFile string, wantDiff bool, allowWrite bool, useColor bool) {
|
|
if !allowWrite {
|
|
fmt.Printf("Key generation requires --write flag\n")
|
|
return
|
|
}
|
|
|
|
config := loadConfig(yamlFile)
|
|
|
|
// Generate keys for each log
|
|
for _, logEntry := range config.Logs {
|
|
// Check if key already exists
|
|
if _, err := os.Stat(logEntry.Secret); err == nil {
|
|
fmt.Printf("Key already exists: %s (skipped)\n", logEntry.Secret)
|
|
continue
|
|
}
|
|
|
|
// Generate new prime256v1 key
|
|
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
|
if err != nil {
|
|
log.Fatalf("Failed to generate key for %s: %v", logEntry.ShortName, err)
|
|
}
|
|
|
|
// Marshal private key to DER format
|
|
privKeyDER, err := x509.MarshalECPrivateKey(privKey)
|
|
if err != nil {
|
|
log.Fatalf("Failed to marshal private key for %s: %v", logEntry.ShortName, err)
|
|
}
|
|
|
|
// Create PEM block
|
|
privKeyPEM := pem.EncodeToMemory(&pem.Block{
|
|
Type: "EC PRIVATE KEY",
|
|
Bytes: privKeyDER,
|
|
})
|
|
|
|
// Ensure directory exists
|
|
if err := os.MkdirAll(filepath.Dir(logEntry.Secret), 0755); err != nil {
|
|
log.Fatalf("Failed to create directory for %s: %v", logEntry.Secret, err)
|
|
}
|
|
|
|
// Write key to file
|
|
err = os.WriteFile(logEntry.Secret, privKeyPEM, 0600)
|
|
if err != nil {
|
|
log.Fatalf("Failed to write key file %s: %v", logEntry.Secret, err)
|
|
}
|
|
|
|
fmt.Printf("Generated %s\n", logEntry.Secret)
|
|
}
|
|
}
|