profilefed/keys.go
2024-03-08 20:56:26 -08:00

105 lines
2.2 KiB
Go

package profilefed
import (
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"errors"
"os"
)
// LoadOrGenerateKeys checks whether the file at path exists. If it does,
// the private and public keys at that path are loaded and returned.
// If not, new keys are generated and saved to the given path.
func LoadOrGenerateKeys(path string) (ed25519.PublicKey, ed25519.PrivateKey, error) {
if _, err := os.Stat(path); err != nil {
return generateKeys(path)
}
return loadKeys(path)
}
func loadKeys(path string) (ed25519.PublicKey, ed25519.PrivateKey, error) {
privData, err := os.ReadFile(path)
if err != nil {
return nil, nil, err
}
pubData, err := os.ReadFile(path + ".pub")
if err != nil {
return nil, nil, err
}
privBlock, _ := pem.Decode(privData)
pubBlock, _ := pem.Decode(pubData)
if privBlock == nil {
return nil, nil, errors.New("invalid private key data")
}
if pubBlock == nil {
return nil, nil, errors.New("invalid public key data")
}
privkey, err := x509.ParsePKCS8PrivateKey(privBlock.Bytes)
if err != nil {
return nil, nil, err
}
pubkey, err := x509.ParsePKIXPublicKey(pubBlock.Bytes)
if err != nil {
return nil, nil, err
}
priv, ok := privkey.(ed25519.PrivateKey)
if !ok {
return nil, nil, errors.New("invalid private key type")
}
pub, ok := pubkey.(ed25519.PublicKey)
if !ok {
return nil, nil, errors.New("invalid public key type")
}
return pub, priv, nil
}
func generateKeys(path string) (ed25519.PublicKey, ed25519.PrivateKey, error) {
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, nil, err
}
privData, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return nil, nil, err
}
privBlock := &pem.Block{
Type: "ED25519 PRIVATE KEY",
Bytes: privData,
}
err = os.WriteFile(path, pem.EncodeToMemory(privBlock), 0o600)
if err != nil {
return nil, nil, err
}
pubData, err := x509.MarshalPKIXPublicKey(pub)
if err != nil {
return nil, nil, err
}
pubBlock := &pem.Block{
Type: "ED25519 PUBLIC KEY",
Bytes: pubData,
}
err = os.WriteFile(path+".pub", pem.EncodeToMemory(pubBlock), 0o644)
if err != nil {
return nil, nil, err
}
return pub, priv, nil
}