aboutsummaryrefslogtreecommitdiff
path: root/key/pub.go
blob: aa23685d2dcd403c4edc7fd65a0a389b45696d79 (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
package key

import (
	"bytes"
	"encoding/binary"

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

type Pub struct {
	PKAlg  [2]byte
	KeyNum [8]byte
	Key    [ed25519.PublicKeySize]byte
}

func (v *Pub) Validate() error {
	if v.PKAlg != pkAlg {
		return ErrInvalidPK
	}
	return nil
}

// NewPub returns a parsed public key
func NewPub(data []byte) (*Pub, error) {
	pub := new(Pub)
	if err := pub.UnmarshalBinary(data); err != nil {
		return nil, err
	}
	return pub, pub.Validate()
}

func (v *Pub) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)
	if err := binary.Write(buf, binary.BigEndian, v); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func (v *Pub) UnmarshalBinary(data []byte) error {
	buf := bytes.NewReader(data)
	if err := binary.Read(buf, binary.BigEndian, v); err != nil {
		return err
	}
	return nil
}