aboutsummaryrefslogtreecommitdiff
path: root/key/enc.go
blob: 6ade4f68bd35c656458b66c3c0b26d93f9b792a1 (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
package key

import (
	"bytes"
	"crypto/sha512"

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

type Enc struct {
	PKAlg     [2]byte
	KDFAlg    [2]byte
	KDFRounds uint32
	Salt      [16]byte
	Checksum  [8]byte
	KeyNum    [8]byte
	Key       [ed25519.PrivateKeySize]byte
}

func (v *Enc) Sign(message []byte) *Sig {
	sig := &Sig{PKAlg: v.PKAlg, KeyNum: v.KeyNum}
	copy(sig.Sig[:], ed25519.Sign(ed25519.PrivateKey(v.Key[:]), message))
	return sig
}

func (v *Enc) Check() error {
	if v.PKAlg != pkAlg {
		return ErrInvalidPK
	}
	if v.KDFAlg != kdfAlg {
		return ErrInvalidKDF
	}
	sum := sha512.Sum512(v.Key[:])
	if !bytes.Equal(sum[:len(v.Checksum)], v.Checksum[:]) {
		return ErrInvalidKey
	}
	return nil
}

func (v *Enc) MarshalBinary() ([]byte, error) {
	return Marshal(v)
}

func (v *Enc) UnmarshalBinary(data []byte) error {
	return Unmarshal(data, v)
}

func ParseEnc(data []byte, d KeyDeriver) (*Enc, error) {
	var enc *Enc
	if err := enc.UnmarshalBinary(data); err != nil {
		return nil, err
	}
	if d != nil && enc.KDFRounds > 0 {
		xor, err := d.DeriveKey(enc.Salt[:], int(enc.KDFRounds), len(enc.Key))
		if err != nil {
			return nil, err
		}
		for i := range xor {
			enc.Key[i] ^= xor[i]
		}
	}
	return enc, enc.Check()
}