-
Notifications
You must be signed in to change notification settings - Fork 127
/
signature.go
118 lines (98 loc) · 2.46 KB
/
signature.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package crypto
import (
"bytes"
"crypto/sha512"
"encoding/hex"
"fmt"
"strconv"
"filippo.io/edwards25519"
)
type Signature [64]byte
func (s *Signature) R() []byte {
return s[:32]
}
func (s *Signature) S() []byte {
return s[32:]
}
func (privateKey *Key) Sign(message Hash) Signature {
var digest1, messageDigest, hramDigest [64]byte
// the hash costs almost nothing compared to elliptic curve ops
h := sha512.New()
h.Write(privateKey[:32])
h.Sum(digest1[:0])
h.Reset()
h.Write(digest1[32:])
h.Write(message[:])
h.Sum(messageDigest[:0])
z, err := edwards25519.NewScalar().SetUniformBytes(messageDigest[:])
if err != nil {
panic(err)
}
R := edwards25519.NewIdentityPoint().ScalarBaseMult(z)
pub := privateKey.Public()
h.Reset()
h.Write(R.Bytes())
h.Write(pub[:])
h.Write(message[:])
h.Sum(hramDigest[:0])
x, err := edwards25519.NewScalar().SetUniformBytes(hramDigest[:])
if err != nil {
panic(err)
}
y, err := edwards25519.NewScalar().SetCanonicalBytes(privateKey[:])
if err != nil {
panic(privateKey.String())
}
s := edwards25519.NewScalar().MultiplyAdd(x, y, z)
var signature Signature
copy(signature[:], R.Bytes())
copy(signature[32:], s.Bytes())
return signature
}
func (publicKey *Key) VerifyWithChallenge(sig Signature, a *edwards25519.Scalar) bool {
p, err := edwards25519.NewIdentityPoint().SetBytes(publicKey[:])
if err != nil {
return false
}
A := edwards25519.NewIdentityPoint().Negate(p)
b, err := edwards25519.NewScalar().SetCanonicalBytes(sig[32:])
if err != nil {
return false
}
R := edwards25519.NewIdentityPoint().VarTimeDoubleScalarBaseMult(a, A, b)
return bytes.Equal(sig[:32], R.Bytes())
}
func (publicKey *Key) Verify(message Hash, sig Signature) bool {
h := sha512.New()
h.Write(sig[:32])
h.Write(publicKey[:])
h.Write(message[:])
var digest [64]byte
h.Sum(digest[:0])
x, err := edwards25519.NewScalar().SetUniformBytes(digest[:])
if err != nil {
panic(err)
}
return publicKey.VerifyWithChallenge(sig, x)
}
func (s Signature) String() string {
return hex.EncodeToString(s[:])
}
func (s Signature) MarshalJSON() ([]byte, error) {
return []byte(strconv.Quote(s.String())), nil
}
func (s *Signature) UnmarshalJSON(b []byte) error {
unquoted, err := strconv.Unquote(string(b))
if err != nil {
return err
}
data, err := hex.DecodeString(string(unquoted))
if err != nil {
return err
}
if len(data) != len(s) {
return fmt.Errorf("invalid signature length %d", len(data))
}
copy(s[:], data)
return nil
}