-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathed25519.go
63 lines (51 loc) · 1.62 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
package httpsignatures
import (
"crypto/ed25519"
"encoding/asn1"
"encoding/pem"
)
const algED25519 = "ED25519"
// ED25519 ED25519 Algorithm
type ED25519 struct{}
// Algorithm Return algorithm name
func (a ED25519) Algorithm() string {
return algED25519
}
// Create Create signature using passed privateKey from secret
func (a ED25519) Create(secret Secret, data []byte) ([]byte, error) {
block, _ := pem.Decode([]byte(secret.PrivateKey))
if block == nil {
return nil, &ErrCrypto{"no private key found", nil}
}
var asn1PrivateKey ED25519PrivateKey
_, err := asn1.Unmarshal(block.Bytes, &asn1PrivateKey)
if err != nil {
return nil, &ErrCrypto{"error unmarshal private key", err}
}
privateKey := ed25519.NewKeyFromSeed(asn1PrivateKey.PrivateKey[2:])
if len(privateKey) != ed25519.PrivateKeySize {
return nil, &ErrCrypto{"invalid private key size", nil}
}
return ed25519.Sign(privateKey, data), nil
}
// Verify Verify signature using passed publicKey from secret
func (a ED25519) Verify(secret Secret, data []byte, signature []byte) error {
block, _ := pem.Decode([]byte(secret.PublicKey))
if block == nil {
return &ErrCrypto{"no public key found", nil}
}
var asn1PublicKey ED25519PublicKey
_, err := asn1.Unmarshal(block.Bytes, &asn1PublicKey)
if err != nil {
return &ErrCrypto{"error unmarshal public key", err}
}
publicKey := ed25519.PublicKey(asn1PublicKey.PublicKey.Bytes)
if len(publicKey) != ed25519.PublicKeySize {
return &ErrCrypto{"invalid public key size", nil}
}
res := ed25519.Verify(publicKey, data, signature)
if !res {
return &ErrCrypto{"signature verification error", nil}
}
return nil
}