@ 4f9fbfd716661e42b7cf2b9f9c44cd9aa9ff450d | history
package lisp2gov
import (
"crypto/ed25519"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"strconv"
)
// DefaultSeed signs programs compiled without an author key. It is public
// on purpose: anyone can rebuild, amend or repeal such a program, and
// `government verify` says so.
var DefaultSeed = sha256.Sum256([]byte("GOVERNMENT"))
// keyForDepth returns the signing key of the cert at depth i (0 is the
// anchor). Deriving every key from one seed keeps output deterministic and
// means the seed's holder alone can rebuild the chain or sign repeals.
func keyForDepth(seed [32]byte, i int) ed25519.PrivateKey {
if i == 0 {
return ed25519.NewKeyFromSeed(seed[:])
}
h := sha256.New()
h.Write(seed[:])
h.Write([]byte("GOVERNMENT"))
h.Write([]byte(strconv.Itoa(i)))
return ed25519.NewKeyFromSeed(h.Sum(nil))
}
// DefaultAnchorKey is the public key of programs compiled without an
// author key, so tools can say when a program is signed by nobody in
// particular.
func DefaultAnchorKey() ed25519.PublicKey {
return keyForDepth(DefaultSeed, 0).Public().(ed25519.PublicKey)
}
// LoadKey reads an author's Ed25519 private key, a PKCS#8 "PRIVATE KEY" PEM
// block such as `openssl genpkey -algorithm ed25519` writes, and returns
// its seed. The seed is the key: Ed25519 derives the whole key pair from
// these 32 bytes, so it is also what keyForDepth derives each depth from.
func LoadKey(data []byte) (*[32]byte, error) {
block, _ := pem.Decode(data)
if block == nil || block.Type != "PRIVATE KEY" {
return nil, errors.New("want a PKCS#8 \"PRIVATE KEY\" PEM block")
}
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
ed, ok := key.(ed25519.PrivateKey)
if !ok {
return nil, fmt.Errorf("the key is a %T; GOVERNMENT signs with Ed25519", key)
}
seed := [32]byte(ed.Seed())
return &seed, nil
}