-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathed25519.go
84 lines (66 loc) · 1.58 KB
/
ed25519.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
74
75
76
77
78
79
80
81
82
83
84
package ed25519
import (
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"github.com/alexfalkowski/go-service/crypto/algo"
"github.com/alexfalkowski/go-service/crypto/errors"
)
// Generate key pair with Ed25519.
func Generate() (string, string, error) {
pu, pr, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return "", "", err
}
mpu, err := x509.MarshalPKIXPublicKey(pu)
if err != nil {
return "", "", err
}
mpr, err := x509.MarshalPKCS8PrivateKey(pr)
if err != nil {
return "", "", err
}
pub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: mpu})
pri := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: mpr})
return string(pub), string(pri), nil
}
// Algo for ed25519.
type Algo interface {
algo.Signer
}
// NewAlgo for ed25519.
func NewAlgo(cfg *Config) (Algo, error) {
if !IsEnabled(cfg) {
return &algo.NoSigner{}, nil
}
pub, err := cfg.PublicKey()
if err != nil {
return nil, err
}
pri, err := cfg.PrivateKey()
if err != nil {
return nil, err
}
return &ed25519Algo{publicKey: pub, privateKey: pri}, nil
}
type ed25519Algo struct {
publicKey ed25519.PublicKey
privateKey ed25519.PrivateKey
}
func (a *ed25519Algo) Sign(msg string) (string, error) {
m := ed25519.Sign(a.privateKey, []byte(msg))
return base64.StdEncoding.EncodeToString(m), nil
}
func (a *ed25519Algo) Verify(sig, msg string) error {
d, err := base64.StdEncoding.DecodeString(sig)
if err != nil {
return err
}
ok := ed25519.Verify(a.publicKey, []byte(msg), d)
if !ok {
return errors.ErrMismatch
}
return nil
}