Debian Codegraph @

vrf/ecvrf.go

raw symbols SCIP
1 // Copyright (c) 2021 Oasis Labs Inc. All rights reserved.
2 // Copyright (c) 2021 Yawning Angel. All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // 1. Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright
12 // notice, this list of conditions and the following disclaimer in the
13 // documentation and/or other materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20 // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
22 // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
25 // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 // Package vrf implements "Verifiable Random Functions (VRFs)" as specified
32 // in RFC 9381, providing the ECVRF-EDWARDS25519-SHA512-ELL2 suite.
33 package vrf
34
35 import (
36 "bytes"
37 "crypto/ed25519"
38 "crypto/sha512"
39 "crypto/subtle"
40 "fmt"
41
42 "filippo.io/edwards25519"
43 "gitlab.com/yawning/edwards25519-extra/h2c"
44 )
45
46 const (
47 // ProofSize is the size, in bytes, of proofs as used in this package.
48 ProofSize = 80
49
50 // OutputSize is the size, in bytes, of outputs as used in this package.
51 OutputSize = 64
52
53 zeroString = 0x00
54 twoString = 0x02
55 threeString = 0x03
56 suiteString = 0x04
57 )
58
59 // The domain separation tag DST, a parameter to the hash-to-curve
60 // suite, SHALL be set to "ECVRF_" || h2c_suite_ID_string || suite_string
61 var h2cDST = []byte{
62 'E', 'C', 'V', 'R', 'F', '_', // "ECVRF_"
63 'e', 'd', 'w', 'a', 'r', 'd', 's', '2', '5', '5', '1', '9', '_', 'X', 'M', 'D', ':', 'S', 'H', 'A', '-', '5', '1', '2', '_', 'E', 'L', 'L', '2', '_', 'N', 'U', '_', // h2c_suite_ID_string
64 suiteString, // suite_string
65 }
66
67 // Prove implements ECVRF_prove for the suite ECVRF-EDWARDS25519-SHA512-ELL2.
68 func Prove(sk ed25519.PrivateKey, alphaString []byte) []byte {
69 return doProve(sk, alphaString, false)
70 }
71
72 // Prove_v10 is Prove but using the draft v7 to v10 semantics.
73 func Prove_v10(sk ed25519.PrivateKey, alphaString []byte) []byte {
74 return doProve(sk, alphaString, true)
75 }
76
77 func doProve(
78 sk ed25519.PrivateKey,
79 alphaString []byte,
80 draftPreV11 bool,
81 ) []byte {
82 // 1. Use SK to derive the VRF secret scalar x and the VRF
83 // public key Y = x*B (this derivation depends on the ciphersuite,
84 // as per Section 5.5; these values can be cached, for example,
85 // after key generation, and need not be rederived each time)
86
87 if len(sk) != ed25519.PrivateKeySize {
88 panic("ecvrf: bad private key length")
89 }
90
91 var extsk [64]byte
92 h := sha512.New()
93 _, _ = h.Write(sk[:32])
94 h.Sum(extsk[:0])
95 x, err := edwards25519.NewScalar().SetBytesWithClamping(extsk[:32])
96 if err != nil {
97 panic("ecvrf: failed to deserialize x scalar: " + err.Error())
98 }
99 extsk[0] &= 248
100 extsk[31] &= 127
101 extsk[31] |= 64
102 Y := sk[32:]
103
104 // 2. H = ECVRF_encode_to_curve(encode_to_curve_salt, alpha_string)
105 H, err := encodeToCurveH2cSuite(Y, alphaString)
106 if err != nil {
107 panic("ecvrf: failed to hash point to curve: " + err.Error())
108 }
109
110 // 3. h_string = point_to_string(H)
111 hString := H.Bytes()
112
113 // 4. Gamma = x*H
114 gamma := edwards25519.NewIdentityPoint().ScalarMult(x, H)
115 gammaString := gamma.Bytes()
116
117 // 5. k = ECVRF_nonce_generation(SK, h_string)
118 var digest [64]byte
119 h.Reset()
120 _, _ = h.Write(extsk[32:])
121 _, _ = h.Write(hString)
122 h.Sum(digest[:0])
123 k, err := edwards25519.NewScalar().SetUniformBytes(digest[:])
124 if err != nil {
125 panic("ecvrf: failed to deserialize k scalar: " + err.Error())
126 }
127
128 // The challenge generation depends on the version of the IETF draft
129 // because they changed things as of draft v11 to include Y in the hash
130 // input.
131 //
132 // Old: c = ECVRF_hash_points(H, Gamma, k*B, k*H) (see Section 5.4.3)
133 // New: c = ECVRF_challenge_generation(Y, H, Gamma, k*B, k*H)
134 //
135 // Handle this in ECVRF_challenge_generation, since it is a matter
136 // of including Y or not.
137
138 var p1 []byte
139 kB := edwards25519.NewIdentityPoint().ScalarBaseMult(k)
140 kH := edwards25519.NewIdentityPoint().ScalarMult(k, H)
141 if !draftPreV11 {
142 p1 = Y
143 }
144 c := challengeGeneration(p1, hString, gammaString, kB, kH)
145
146 // 7. s = (k + c*x) mod q
147 s := edwards25519.NewScalar().Multiply(c, x)
148 s.Add(s, k)
149
150 // 8. pi_string = point_to_string(Gamma) || int_to_string(c, n) ||
151 // int_to_string(s, qLen)
152 var piString [ProofSize]byte
153 copy(piString[:32], gammaString)
154 copy(piString[32:], c.Bytes())
155 copy(piString[48:], s.Bytes()) // c is truncated (128-bits).
156
157 // 9. Output pi_string
158 return piString[:]
159 }
160
161 // ProofToHash implements ECVRF_proof_to_hash for the suite ECVRF-EDWARDS25519-SHA512-ELL2.
162 //
163 // ECVRF_proof_to_hash should be run only on pi_string that is known
164 // to have been produced by ECVRF_prove, or from within ECVRF_verify.
165 func ProofToHash(piString []byte) ([]byte, error) {
166 // 1. D = ECVRF_decode_proof(pi_string) (see Section 5.4.4)
167 // 2. If D is "INVALID", output "INVALID" and stop
168 // 3. (Gamma, c, s) = D
169 gamma, _, _, err := decodeProof(piString)
170 if err != nil {
171 return nil, fmt.Errorf("ecvrf: failed to decode proof: %w", err)
172 }
173
174 // Steps 4 .. 7 are in gammaToHash.
175 return gammaToHash(gamma), nil
176 }
177
178 // Verify implements ECVRF_verify for the suite ECVRF-EDWARDS25519-SHA512-ELL2.
179 //
180 // The public key is validated such that the "full uniqueness" and
181 // "full collision" properties are satisfied.
182 func Verify(pk ed25519.PublicKey, piString, alphaString []byte) (bool, []byte) {
183 return doVerify(pk, piString, alphaString, false)
184 }
185
186 // Verify_v10 is Verify but using the draft v7 to v10 semantics.
187 func Verify_v10(pk ed25519.PublicKey, piString, alphaString []byte) (bool, []byte) {
188 return doVerify(pk, piString, alphaString, true)
189 }
190
191 func doVerify(
192 pk ed25519.PublicKey,
193 piString []byte,
194 alphaString []byte,
195 draftPreV11 bool,
196 ) (bool, []byte) {
197 // 1. Y = string_to_point(PK_string)
198 yString := pk
199 Y, err := edwards25519.NewIdentityPoint().SetBytes(yString)
200 if err != nil {
201 return false, nil
202 }
203 // 2. If Y is "INVALID", output "INVALID" and stop
204 if !bytes.Equal(Y.Bytes(), yString) { // Required by RFC 8032 decode semantics.
205 return false, nil
206 }
207 // 3. If validate_key, run ECVRF_validate_key(Y) (Section 5.4.5); if
208 // it outputs "INVALID", output "INVALID" and stop
209 cY := edwards25519.NewIdentityPoint().MultByCofactor(Y)
210 if cY.Equal(edwards25519.NewIdentityPoint()) == 1 { // Section 5.6.1 ECVRF Validate Key
211 return false, nil
212 }
213
214 // 4. D = ECVRF_decode_proof(pi_string) (see Section 5.4.4)
215 // 5. If D is "INVALID", output "INVALID" and stop
216 // 6. (Gamma, c, s) = D
217 gamma, c, s, err := decodeProof(piString)
218 if err != nil {
219 return false, nil
220 }
221 gammaString := piString[:32]
222
223 // 7. H = ECVRF_encode_to_curve(encode_to_curve_salt, alpha_string)
224 // (see Section 5.4.1)
225 H, err := encodeToCurveH2cSuite(yString, alphaString)
226 if err != nil {
227 panic("ecvrf: failed to hash point to curve: " + err.Error())
228 }
229 hString := H.Bytes()
230
231 // 8. U = s*B - c*Y
232 Y.Negate(Y)
233 U := edwards25519.NewIdentityPoint().VarTimeDoubleScalarBaseMult(c, Y, s)
234
235 // 9. V = s*H - c*Gamma
236 negGamma := edwards25519.NewIdentityPoint().Negate(gamma)
237 V := edwards25519.NewIdentityPoint().VarTimeMultiScalarMult(
238 []*edwards25519.Scalar{s, c},
239 []*edwards25519.Point{H, negGamma},
240 )
241
242 // 10. c' = ECVRF_challenge_generation(Y, H, Gamma, U, V) (see
243 // Section 5.4.3)
244 //
245 // Note: Old (pre-v11) versions of the draft did not include Y,
246 // and instead did c' = ECVRF_hash_points(H, Gamma, U, V).
247 var p1 []byte
248 if !draftPreV11 {
249 p1 = pk[:]
250 }
251 cPrime := challengeGeneration(p1, hString, gammaString, U, V)
252
253 // 11. If c and c' are equal, output ("VALID",
254 // ECVRF_proof_to_hash(pi_string)); else output "INVALID"
255
256 if c.Equal(cPrime) == 0 {
257 return false, nil
258 }
259 return true, gammaToHash(gamma)
260 }
261
262 func gammaToHash(gamma *edwards25519.Point) []byte {
263 // 4. three_string = 0x03 = int_to_string(3, 1), a single octet with
264 // value 3
265 // 5. zero_string = 0x00 = int_to_string(0, 1), a single octet with
266 // value 0
267 // 6. beta_string = Hash(suite_string || three_string ||
268 // point_to_string(cofactor * Gamma) || zero_string)
269 // 7. Output beta_string
270 cG := edwards25519.NewIdentityPoint().MultByCofactor(gamma)
271 h := sha512.New()
272 _, _ = h.Write([]byte{suiteString, threeString}) // suite_string, three_string
273 _, _ = h.Write(cG.Bytes()) // point_to_string(cofactor * Gamma)
274 _, _ = h.Write([]byte{zeroString}) // zero_string
275 return h.Sum(nil)
276 }
277
278 func encodeToCurveH2cSuite(encodeToCurveSalt, alphaString []byte) (*edwards25519.Point, error) {
279 // For the Edwards25519 curve:
280 // PK_string = point_to_string(Y)
281 // encode_to_curve_salt = PK_string
282
283 // 1. string_to_be_hashed = encode_to_curve_salt || alpha_string
284 stringToHash := make([]byte, 0, len(encodeToCurveSalt)+len(alphaString))
285 stringToHash = append(stringToHash, encodeToCurveSalt...)
286 stringToHash = append(stringToHash, alphaString...)
287
288 // 2. H = encode(string_to_hash)
289 // 3. Output H
290 return h2c.Edwards25519_XMD_SHA512_ELL2_NU(h2cDST, stringToHash)
291 }
292
293 func challengeGeneration(p1, p2, p3 []byte, p4, p5 *edwards25519.Point) *edwards25519.Scalar {
294 // 1. challenge_generation_domain_separator_front = 0x02
295 // 2. Initialize str = suite_string || challenge_generation_domain_separator_front
296 var digest [64]byte
297 h := sha512.New()
298 _, _ = h.Write([]byte{suiteString, twoString}) // suite_string || challenge_generation_domain_separator_front
299
300 // 3. for PJ in [P1, P2, P3, P4, P5]:
301 // str = str || point_to_string(PJ)
302 if len(p1) > 0 {
303 // This needs to handle both pre-v11 where Y was not included,
304 // and v11 and later, where Y is included. This branch is the
305 // latter.
306 _, _ = h.Write(p1) // point_to_string(P1)
307 }
308 _, _ = h.Write(p2) // point_to_string(P2)
309 _, _ = h.Write(p3) // point_to_string(P3)
310 _, _ = h.Write(p4.Bytes()) // point_to_string(P3)
311 _, _ = h.Write(p5.Bytes()) // point_to_string(P4)
312
313 // 4. challenge_generation_domain_separator_back = 0x00
314 // 5. str = str || challenge_generation_domain_separator_back
315 _, _ = h.Write([]byte{zeroString}) // challenge_generation_domain_separator_back
316
317 // 6. c_string = Hash(str)
318 h.Sum(digest[:0])
319
320 // 7. truncated_c_string = c_string[0]...c_string[n-1]
321 // 8. c = string_to_int(truncated_c_string)
322 var cString [32]byte
323 copy(cString[:16], digest[:16])
324 c, err := edwards25519.NewScalar().SetCanonicalBytes(cString[:])
325 if err != nil {
326 panic("ecvrf: failed to deserialize c scalar: " + err.Error())
327 }
328
329 // 9. Output c
330 return c
331 }
332
333 func decodeProof(piString []byte) (*edwards25519.Point, *edwards25519.Scalar, *edwards25519.Scalar, error) {
334 if l := len(piString); l != ProofSize {
335 return nil, nil, nil, fmt.Errorf("ecvrf: invalid proof size: %d", l)
336 }
337
338 // 1. let gamma_string = pi_string[0]...pi_string[ptLen-1]
339 // 2. let c_string = pi_string[ptLen]...pi_string[ptLen+n-1]
340 // 3. let s_string =pi_string[ptLen+n]...pi_string[ptLen+n+qLen-1]
341
342 // 4. Gamma = string_to_point(gamma_string)
343 // 5. if Gamma = "INVALID" output "INVALID" and stop.
344 gammaString := piString[:32]
345 gamma, err := edwards25519.NewIdentityPoint().SetBytes(gammaString[:32])
346 if err != nil {
347 return nil, nil, nil, fmt.Errorf("ecvrf: failed to decompress gamma: %w", err)
348 }
349 if subtle.ConstantTimeCompare(gamma.Bytes(), gammaString) != 1 { // Required by RFC 8032 decode semantics.
350 return nil, nil, nil, fmt.Errorf("ecvrf: non-canonical gamma")
351 }
352
353 // 6. c = string_to_int(c_string)
354 var cString [32]byte
355 copy(cString[:16], piString[32:])
356 c, err := edwards25519.NewScalar().SetCanonicalBytes(cString[:])
357 if err != nil {
358 return nil, nil, nil, fmt.Errorf("ecvrf: failed to deserialize c scalar: %w", err)
359 }
360
361 // 7. s = string_to_int(s_string)
362 s, err := edwards25519.NewScalar().SetCanonicalBytes(piString[48:])
363 if err != nil {
364 return nil, nil, nil, fmt.Errorf("ecvrf: failed to deserialize s scalar: %w", err)
365 }
366 // 8. if s >= q output "INVALID" and stop
367 if subtle.ConstantTimeCompare(s.Bytes(), piString[48:]) != 1 {
368 return nil, nil, nil, fmt.Errorf("ecvrf: non-canonical s scalar")
369 }
370
371 // 9. Output Gamma, c, and s
372 return gamma, c, s, nil
373 }