aboutsummaryrefslogtreecommitdiff
path: root/key/gen.go
blob: 39436a1af5ededa61d4628a4fcdc39b1555b1949 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Package key implements signify key format
package key

import (
	"crypto/rand"
	"crypto/sha512"
	"errors"

	"golang.org/x/crypto/ed25519"
)

const kdfRounds = 42

var (
	ErrInvalidPK  = errors.New("unsupported format")
	ErrInvalidKDF = errors.New("unsupported KDF")
	ErrInvalidKey = errors.New("invalid key")
	ErrKeyNum     = errors.New("verification failed: checked against wrong key")
	ErrInvalidSig = errors.New("signature verfication failed")
)

var (
	pkAlg  = [2]byte{'E', 'd'}
	kdfAlg = [2]byte{'B', 'K'}
)

// Deriver returns a derived encryption key
type Deriver interface {
	Derive(salt []byte, rounds int, length int) ([]byte, error)
}

// Generate a new key pair
func Generate(der Deriver) (*Pub, *Sec, error) {
	pubKey, secKey, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	// secret key
	sec := &Sec{PKAlg: pkAlg, KDFAlg: kdfAlg}
	copy(sec.Key[:], secKey)

	checkSum := sha512.Sum512(secKey)
	copy(sec.Checksum[:], checkSum[:len(sec.Checksum)])

	if _, err := rand.Read(sec.Salt[:]); err != nil {
		return nil, nil, err
	}
	if _, err := rand.Read(sec.KeyNum[:]); err != nil {
		return nil, nil, err
	}

	// Pbdkf
	if der != nil {
		sec.KDFRounds = kdfRounds
	}
	if err := sec.Crypt(der); err != nil {
		return nil, nil, err
	}

	// public key
	pub := &Pub{PKAlg: pkAlg, KeyNum: sec.KeyNum}
	copy(pub.Key[:], pubKey)

	return pub, sec, nil
}