-
Notifications
You must be signed in to change notification settings - Fork 0
/
smolcert.go
73 lines (64 loc) · 2.31 KB
/
smolcert.go
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
package krach
import (
"errors"
"github.com/iost-official/ed25519/extra25519"
"github.com/smolcert/smolcert"
"golang.org/x/crypto/ed25519"
)
// Identity wraps a smolcert based certificate and provides the public
// key as curve25519 representation instead of ed25519
type Identity struct {
smolcert.Certificate
}
// PublicKey returns the curve25519 representation of the ed25519 public key of this certificate
func (s *Identity) PublicKey() [32]byte {
// The certificates used by Smolcert use ed25519 keys, but we need curve25519 keys.
// As they both are based on the same curve, we can convert them.
var curvePubKey [32]byte
var edPubKey [32]byte
copy(edPubKey[:], s.Certificate.PubKey)
if !extra25519.PublicKeyToCurve25519(&curvePubKey, &edPubKey) {
// Signal that we couldn't create a valid curve25519 representation
panic("Failed to convert ed25519 public to curve25519 public key")
}
return curvePubKey
}
// Cert returns the plain smolcert certificate
func (s *Identity) Cert() *smolcert.Certificate {
return &s.Certificate
}
// PrivateIdentity wraps a SmolIdentity and an ed25519 private key
type PrivateIdentity struct {
Identity
privKey ed25519.PrivateKey
}
// NewPrivateIdentity creates a new PrivateSmolIdentity which contains the smolcert with the private key.
// This might be needed for cryptographic operations like eDH or eDSA etc.
func NewPrivateIdentity(cert *smolcert.Certificate, privKey ed25519.PrivateKey) (*PrivateIdentity, error) {
msg := []byte("His name was Gaal Dornick and he was just a country boy who had never seen Trantor before. ")
sig := ed25519.Sign(privKey, msg)
if !ed25519.Verify(cert.PubKey, msg, sig) {
return nil, errors.New("private key and public key of certificate do not belong to each other")
}
return &PrivateIdentity{
Identity: Identity{
Certificate: *cert,
},
privKey: privKey,
}, nil
}
func MustNewPrivateIdentity(cert *smolcert.Certificate, privKey ed25519.PrivateKey) *PrivateIdentity {
id, err := NewPrivateIdentity(cert, privKey)
if err != nil {
panic(err)
}
return id
}
// PrivateKey returns a curve25519 representation of the private key
func (p *PrivateIdentity) PrivateKey() [32]byte {
var edPrivKey [64]byte
var curvePrivKey [32]byte
copy(edPrivKey[:], p.privKey)
extra25519.PrivateKeyToCurve25519(&curvePrivKey, &edPrivKey)
return curvePrivKey
}