File: keys.go

package info (click to toggle)
golang-github-endophage-gotuf 0.0~git20151020.0.2df1c8e-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 436 kB
  • ctags: 504
  • sloc: makefile: 27
file content (96 lines) | stat: -rw-r--r-- 1,878 bytes parent folder | download
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
90
91
92
93
94
95
96
package data

import (
	"crypto/sha256"
	"encoding/hex"

	"github.com/Sirupsen/logrus"
	"github.com/jfrazelle/go/canonical/json"
)

type Key interface {
	ID() string
	Algorithm() KeyAlgorithm
	Public() []byte
}

type PublicKey interface {
	Key
}

type PrivateKey interface {
	Key

	Private() []byte
}

type KeyPair struct {
	Public  []byte `json:"public"`
	Private []byte `json:"private"`
}

// TUFKey is the structure used for both public and private keys in TUF.
// Normally it would make sense to use a different structures for public and
// private keys, but that would change the key ID algorithm (since the canonical
// JSON would be different). This structure should normally be accessed through
// the PublicKey or PrivateKey interfaces.
type TUFKey struct {
	id    string       `json:"-"`
	Type  KeyAlgorithm `json:"keytype"`
	Value KeyPair      `json:"keyval"`
}

func NewPrivateKey(algorithm KeyAlgorithm, public, private []byte) *TUFKey {
	return &TUFKey{
		Type: algorithm,
		Value: KeyPair{
			Public:  public,
			Private: private,
		},
	}
}

func (k TUFKey) Algorithm() KeyAlgorithm {
	return k.Type
}

func (k *TUFKey) ID() string {
	if k.id == "" {
		pubK := NewPublicKey(k.Algorithm(), k.Public())
		data, err := json.MarshalCanonical(&pubK)
		if err != nil {
			logrus.Error("Error generating key ID:", err)
		}
		digest := sha256.Sum256(data)
		k.id = hex.EncodeToString(digest[:])
	}
	return k.id
}

func (k TUFKey) Public() []byte {
	return k.Value.Public
}

func (k TUFKey) Private() []byte {
	return k.Value.Private
}

func NewPublicKey(algorithm KeyAlgorithm, public []byte) PublicKey {
	return &TUFKey{
		Type: algorithm,
		Value: KeyPair{
			Public:  public,
			Private: nil,
		},
	}
}

func PublicKeyFromPrivate(pk PrivateKey) PublicKey {
	return &TUFKey{
		Type: pk.Algorithm(),
		Value: KeyPair{
			Public:  pk.Public(),
			Private: nil,
		},
	}
}