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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
// Package key implements signify key format
package key
import (
"bytes"
"crypto/rand"
"crypto/sha512"
"encoding/binary"
"errors"
"golang.org/x/crypto/ed25519"
)
// DefaultRounds of KDF
const DefaultRounds = 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 key from passphrase
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 {
xor, err := der.Derive(sec.Salt[:], DefaultRounds, len(sec.Key))
if err != nil {
return nil, nil, err
}
for i := range xor {
sec.Key[i] ^= xor[i]
}
sec.KDFRounds = DefaultRounds
}
// public key
pub := &Pub{PKAlg: pkAlg, KeyNum: sec.KeyNum}
copy(pub.Key[:], pubKey)
return pub, sec, nil
}
func unmarshal(data []byte, v interface{}) error {
buf := bytes.NewReader(data)
if err := binary.Read(buf, binary.BigEndian, v); err != nil {
return err
}
return nil
}
func marshal(v interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
if err := binary.Write(buf, binary.BigEndian, v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
|