aboutsummaryrefslogtreecommitdiff
path: root/keys.go
blob: 53dd536c93cb2b9e893057ab7a99f24ec0b80be9 (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
67
68
69
70
71
72
73
74
75
76
77
78
package main

import (
	"bytes"
	"crypto/sha512"
	"encoding/base64"
	"encoding/binary"

	"dim13.org/signify/bhash"

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

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

type Sig struct {
	PKAlg  [2]byte
	KeyNum uint64
	Sig    [ed25519.SignatureSize]byte
}

type PubKey struct {
	PKAlg  [2]byte
	KeyNum uint64
	PubKey [ed25519.PublicKeySize]byte
}

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

func (v *EncKey) XOR(key []byte) {
	if len(key) != len(v.SecKey) {
		panic("invalid key len")
	}
	for i := range key {
		v.SecKey[i] ^= key[i]
	}
}

func (v *EncKey) IsValid(pass []byte) bool {
	if v.KDFRounds > 0 {
		key := bhash.Pbkdf(pass, v.Salt[:], int(v.KDFRounds), len(v.SecKey))
		v.XOR(key)
	}
	sum := sha512.Sum512(v.SecKey[:])
	return bytes.Equal(sum[:len(v.Checksum)], v.Checksum[:])
}

func Unmarshal(b []byte, v interface{}) error {
	buf := bytes.NewReader(b)
	dec := base64.NewDecoder(base64.StdEncoding, buf)
	if err := binary.Read(dec, binary.BigEndian, v); err != nil {
		return err
	}
	return nil
}

func Marshal(v interface{}) ([]byte, error) {
	buf := new(bytes.Buffer)
	enc := base64.NewEncoder(base64.StdEncoding, buf)
	if err := binary.Write(enc, binary.BigEndian, v); err != nil {
		return nil, err
	}
	if err := enc.Close(); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}