| 1 | // Pure Go implementation of the Ristretto prime-order group built from |
| 2 | // the Edwards curve Edwards25519. |
| 3 | // |
| 4 | // Many cryptographic schemes need a group of prime order. Popular and |
| 5 | // efficient elliptic curves like (Edwards25519 of `ed25519` fame) are |
| 6 | // rarely of prime order. There is, however, a convenient method |
| 7 | // to construct a prime order group from such curves, using a method |
| 8 | // called Ristretto proposed by Mike Hamburg. |
| 9 | // |
| 10 | // This package implements the Ristretto group constructed from Edwards25519. |
| 11 | // The Point type represents a group element. The API mimics that of the |
| 12 | // math/big package. For instance, to set c to a+b, one writes |
| 13 | // |
| 14 | // var c ristretto.Point |
| 15 | // c.Add(&a, &b) // sets c to a + b |
| 16 | // |
| 17 | // Warning: contrary to math.Big's interface, an uninitialized Point is not |
| 18 | // the same thing as the zero (neutral element) of the group: |
| 19 | // |
| 20 | // var c ristretto.Point // c is uninitialized now --- not zero! |
| 21 | // c.SetZero() // c is zero now; ready to use! |
| 22 | // |
| 23 | // Most methods return the receiver, so that function can be chained: |
| 24 | // |
| 25 | // s.Add(&a, &b).Add(&s, &c) // sets s to a + b + c |
| 26 | // |
| 27 | // The order of the Ristretto group is l = |
| 28 | // 2^252 + 27742317777372353535851937790883648493 = |
| 29 | // 7237005577332262213973186563042994240857116359379907606001950938285454250989. |
| 30 | // The Scalar type implement the numbers modulo l and also has an API similar |
| 31 | // to math/big. |
| 32 | package ristretto |
| 33 | |
| 34 | import ( |
| 35 | "crypto/rand" |
| 36 | "crypto/sha256" |
| 37 | "crypto/sha512" |
| 38 | "crypto/subtle" |
| 39 | "encoding/base64" |
| 40 | "encoding/hex" |
| 41 | "errors" |
| 42 | "fmt" |
| 43 | |
| 44 | "github.com/bwesterb/go-ristretto/edwards25519" |
| 45 | ) |
| 46 | |
| 47 | // Represents an element of the Ristretto group over Edwards25519. |
| 48 | // |
| 49 | // Warning: an uninitialized Point is not the same thing as a zero. Use |
| 50 | // the SetZero() method to set an (uninitialized) Point to zero. |
| 51 | type Point edwards25519.ExtendedPoint |
| 52 | |
| 53 | // A table to speed up scalar multiplication of a fixed point |
| 54 | type ScalarMultTable edwards25519.ScalarMultTable |
| 55 | |
| 56 | // Sets p to zero (the neutral element). Returns p. |
| 57 | func (p *Point) SetZero() *Point { |
| 58 | p.e().SetZero() |
| 59 | return p |
| 60 | } |
| 61 | |
| 62 | // Sets p to the Edwards25519 basepoint. Returns p |
| 63 | func (p *Point) SetBase() *Point { |
| 64 | p.e().SetBase() |
| 65 | return p |
| 66 | } |
| 67 | |
| 68 | // Sets p to q. Returns p |
| 69 | func (p *Point) Set(q *Point) *Point { |
| 70 | p.e().Set(q.e()) |
| 71 | return p |
| 72 | } |
| 73 | |
| 74 | // Sets p to q + r. Returns p. |
| 75 | func (p *Point) Add(q, r *Point) *Point { |
| 76 | p.e().Add(q.e(), r.e()) |
| 77 | return p |
| 78 | } |
| 79 | |
| 80 | // Sets p to q + q. Returns p. |
| 81 | func (p *Point) Double(q *Point) *Point { |
| 82 | p.e().Double(q.e()) |
| 83 | return p |
| 84 | } |
| 85 | |
| 86 | // Sets p to q - r. Returns p. |
| 87 | func (p *Point) Sub(q, r *Point) *Point { |
| 88 | p.e().Sub(q.e(), r.e()) |
| 89 | return p |
| 90 | } |
| 91 | |
| 92 | // Sets p to -q. Returns p. |
| 93 | func (p *Point) Neg(q *Point) *Point { |
| 94 | p.e().Neg(q.e()) |
| 95 | return p |
| 96 | } |
| 97 | |
| 98 | // Packs p into the given buffer. Returns p. |
| 99 | func (p *Point) BytesInto(buf *[32]byte) *Point { |
| 100 | p.e().RistrettoInto(buf) |
| 101 | return p |
| 102 | } |
| 103 | |
| 104 | // Returns a packed version of p. |
| 105 | func (p *Point) Bytes() []byte { |
| 106 | return p.e().Ristretto() |
| 107 | } |
| 108 | |
| 109 | // Sets p to the point encoded in buf using Bytes(). |
| 110 | // Not every input encodes a point. Returns whether the buffer encoded a point. |
| 111 | func (p *Point) SetBytes(buf *[32]byte) bool { |
| 112 | return p.e().SetRistretto(buf) |
| 113 | } |
| 114 | |
| 115 | // Sets p to the point corresponding to buf using the Elligator2 encoding. |
| 116 | // |
| 117 | // In contrast to SetBytes() (1) Every input buffer will decode to a point |
| 118 | // and (2) SetElligator() is not injective: for every point there are |
| 119 | // approximately four buffers that will encode to it. |
| 120 | func (p *Point) SetElligator(buf *[32]byte) *Point { |
| 121 | var fe edwards25519.FieldElement |
| 122 | var cp edwards25519.CompletedPoint |
| 123 | fe.SetBytes(buf) |
| 124 | cp.SetRistrettoElligator2(&fe) |
| 125 | p.e().SetCompleted(&cp) |
| 126 | return p |
| 127 | } |
| 128 | |
| 129 | // Sets p to s * q, where q is the point for which the table t was |
| 130 | // computed. Returns p. |
| 131 | func (p *Point) ScalarMultTable(t *ScalarMultTable, s *Scalar) *Point { |
| 132 | var buf [32]byte |
| 133 | s.BytesInto(&buf) |
| 134 | t.t().ScalarMult(p.e(), &buf) |
| 135 | return p |
| 136 | } |
| 137 | |
| 138 | // Sets p to s * q, where q is the point for which the table t was |
| 139 | // computed. Returns p. |
| 140 | // |
| 141 | // Warning: this method uses a non-constant time implementation and thus leaks |
| 142 | // information about s. Use this function only if s is public knowledge. |
| 143 | func (p *Point) PublicScalarMultTable(t *ScalarMultTable, s *Scalar) *Point { |
| 144 | var buf [32]byte |
| 145 | s.BytesInto(&buf) |
| 146 | t.t().VarTimeScalarMult(p.e(), &buf) |
| 147 | return p |
| 148 | } |
| 149 | |
| 150 | // Sets p to s * q. Returns p. |
| 151 | func (p *Point) ScalarMult(q *Point, s *Scalar) *Point { |
| 152 | var buf [32]byte |
| 153 | s.BytesInto(&buf) |
| 154 | p.e().ScalarMult(q.e(), &buf) |
| 155 | return p |
| 156 | } |
| 157 | |
| 158 | // Sets p to s * q assuming s is *not* secret. Returns p. |
| 159 | // |
| 160 | // Warning: this method uses a non-constant time implementation and thus leaks |
| 161 | // information about s. Use this function only if s is public knowledge. |
| 162 | func (p *Point) PublicScalarMult(q *Point, s *Scalar) *Point { |
| 163 | var buf [32]byte |
| 164 | s.BytesInto(&buf) |
| 165 | p.e().VarTimeScalarMult(q.e(), &buf) |
| 166 | return p |
| 167 | } |
| 168 | |
| 169 | // Sets p to s * B, where B is the edwards25519 basepoint. Returns p. |
| 170 | // |
| 171 | // Warning: this method uses a non-constant time implementation and thus leaks |
| 172 | // information about s. Use this function only if s is public knowledge. |
| 173 | func (p *Point) PublicScalarMultBase(s *Scalar) *Point { |
| 174 | var buf [32]byte |
| 175 | s.BytesInto(&buf) |
| 176 | edwards25519.BaseScalarMultTable.VarTimeScalarMult(p.e(), &buf) |
| 177 | return p |
| 178 | } |
| 179 | |
| 180 | // Sets p to s * B, where B is the edwards25519 basepoint. Returns p. |
| 181 | func (p *Point) ScalarMultBase(s *Scalar) *Point { |
| 182 | var buf [32]byte |
| 183 | s.BytesInto(&buf) |
| 184 | edwards25519.BaseScalarMultTable.ScalarMult(p.e(), &buf) |
| 185 | return p |
| 186 | } |
| 187 | |
| 188 | // Sets p to a random point. Returns p. |
| 189 | func (p *Point) Rand() *Point { |
| 190 | var buf [32]byte |
| 191 | if _, err := rand.Read(buf[:]); err != nil { |
| 192 | panic(err) |
| 193 | } |
| 194 | return p.SetElligator(&buf) |
| 195 | } |
| 196 | |
| 197 | // Sets p to the point derived from the buffer using SHA512 and Elligator2. |
| 198 | // Returns p. |
| 199 | // |
| 200 | // NOTE curve25519-dalek uses a different (more conservative) method to derive |
| 201 | // a point from raw data with a hash. This is implemented in |
| 202 | // Point.DeriveDalek(). |
| 203 | func (p *Point) Derive(buf []byte) *Point { |
| 204 | var ptBuf [32]byte |
| 205 | h := sha512.Sum512(buf) |
| 206 | copy(ptBuf[:], h[:32]) |
| 207 | return p.SetElligator(&ptBuf) |
| 208 | } |
| 209 | |
| 210 | // Encode 16 bytes into a point using the Lizard method. |
| 211 | // |
| 212 | // Use Lizard() or LizardInto() to decode the bytes from a Point. |
| 213 | // |
| 214 | // Notes on usage: |
| 215 | // |
| 216 | // - If you want to create a Point from random data, you should rather |
| 217 | // create a random Point with Point.Rand() and then use (a hash of) |
| 218 | // Point.Bytes() as the random data. |
| 219 | // |
| 220 | // - If you want to derive a Point from data, but you do not care about |
| 221 | // decoding the data back from the point, you should use |
| 222 | // the Point.Derive() method instead. |
| 223 | // |
| 224 | // - There are some (and with high probability at most 80) inputs to |
| 225 | // SetLizard() which cannot be decoded. The chance that you hit such |
| 226 | // an input is around 1 in 2^122. |
| 227 | // |
| 228 | // In Lizard there are 256 - 128 - 3 = 125 check bits to pick out the |
| 229 | // right preimage among at most eight. Conservatively assuming there are |
| 230 | // seven other preimages, the chance that one of them passes the check as |
| 231 | // well is given by: |
| 232 | // |
| 233 | // 1 - (1 - 2^-125)^7 = 7*2^-125 + 21*2^-250 - ... |
| 234 | // =~ 2^(-125 - 2log(7)) |
| 235 | // = 2^-122.192... |
| 236 | // |
| 237 | // Presuming a random hash function, the number of "bad" inputs is binomially |
| 238 | // distributed with n=2^128 and p=2^-122.192... For such large n, the Poisson |
| 239 | // distribution with lambda=n*p=56 is a very good approximation. In fact: |
| 240 | // the cumulative distribution function (CDF) of the Poission distribution |
| 241 | // is larger than that of the binomial distribution for k > lambda.[1] The value |
| 242 | // of the former on k=80 is larger than 0.999 and so with a probability of 99.9%, |
| 243 | // there are fewer than 80 bad inputs. |
| 244 | // |
| 245 | // [1] See "Some Inequalities Among Binomial and Poisson Probabilities" |
| 246 | // by Anderson and Samuels in Proc. Fifth Berkeley Symp. on |
| 247 | // Math. Statist. and Prob., Vol. 1 (Univ. of Calif. Press, 1967). |
| 248 | func (p *Point) SetLizard(data *[16]byte) *Point { |
| 249 | var fe edwards25519.FieldElement |
| 250 | var cp edwards25519.CompletedPoint |
| 251 | buf := sha256.Sum256(data[:]) |
| 252 | copy(buf[8:], data[:]) |
| 253 | buf[0] &= 254 // clear lowest bit to make the FieldElement positive |
| 254 | buf[31] &= 63 // clear highest two bits to ensure below 2^255-19. |
| 255 | fe.SetBytes(&buf) |
| 256 | cp.SetRistrettoElligator2(&fe) |
| 257 | p.e().SetCompleted(&cp) |
| 258 | return p |
| 259 | } |
| 260 | |
| 261 | // Decodes 16 bytes encoded into this point using SetLizard(). |
| 262 | // |
| 263 | // Returns nil if this point does not contain data encoded using Lizard. |
| 264 | // |
| 265 | // See SetLizard() for notes on usage. |
| 266 | func (p *Point) Lizard() []byte { |
| 267 | var ret [16]byte |
| 268 | if p.LizardInto(&ret) != nil { |
| 269 | return nil |
| 270 | } |
| 271 | return ret[:] |
| 272 | } |
| 273 | |
| 274 | // Decodes 16 bytes into the given buffer encoded into this point |
| 275 | // using SetLizard(). |
| 276 | // |
| 277 | // See SetLizard() for notes on usage. |
| 278 | func (p *Point) LizardInto(buf *[16]byte) error { |
| 279 | var fes [8]edwards25519.FieldElement |
| 280 | var buf2 [32]byte |
| 281 | var nFound uint8 |
| 282 | |
| 283 | mask := p.e().RistrettoElligator2Inverse(&fes) |
| 284 | |
| 285 | for j := 0; j < 8; j++ { |
| 286 | ok := (mask >> uint(j)) & 1 |
| 287 | fes[j].BytesInto(&buf2) |
| 288 | h := sha256.Sum256(buf2[8:24]) |
| 289 | copy(h[8:], buf2[8:24]) |
| 290 | h[0] &= 254 |
| 291 | h[31] &= 63 |
| 292 | ok &= uint8(subtle.ConstantTimeCompare(h[:], buf2[:])) |
| 293 | subtle.ConstantTimeCopy(int(ok), buf[:], buf2[8:24]) |
| 294 | nFound += ok |
| 295 | } |
| 296 | if nFound == 1 { |
| 297 | return nil |
| 298 | } |
| 299 | if nFound == 0 { |
| 300 | return errors.New("No Lizard preimage") |
| 301 | } |
| 302 | return errors.New("Multiple Lizard preimages") |
| 303 | } |
| 304 | |
| 305 | // Returns 1 if p == q and 0 otherwise. |
| 306 | func (p *Point) EqualsI(q *Point) int32 { |
| 307 | return p.e().RistrettoEqualsI(q.e()) |
| 308 | } |
| 309 | |
| 310 | // Returns whether p == q |
| 311 | func (p *Point) Equals(q *Point) bool { |
| 312 | return p.EqualsI(q) == 1 |
| 313 | } |
| 314 | |
| 315 | // Set p to q if b=1 in constant-time. b must be either 0 or 1. |
| 316 | func (p *Point) ConditionalSet(q *Point, b int32) { |
| 317 | p.e().ConditionalSet(q.e(), b) |
| 318 | } |
| 319 | |
| 320 | // Sets p to the point derived from the buffer using SHA512 and Elligator2 |
| 321 | // in the fashion of curve25519-dalek. |
| 322 | // |
| 323 | // NOTE See also Derive(), which is a different method which is twice as fast, |
| 324 | // but which might not be as secure as this method. |
| 325 | func (p *Point) DeriveDalek(data []byte) *Point { |
| 326 | hash := sha512.Sum512(data) |
| 327 | var p2 Point |
| 328 | var buf [32]byte |
| 329 | copy(buf[:], hash[:32]) |
| 330 | p.SetElligator(&buf) |
| 331 | copy(buf[:], hash[32:]) |
| 332 | p2.SetElligator(&buf) |
| 333 | p.Add(p, &p2) |
| 334 | return p |
| 335 | } |
| 336 | |
| 337 | // Implements encoding/BinaryUnmarshaler. Use SetBytes, if convenient, instead. |
| 338 | func (p *Point) UnmarshalBinary(data []byte) error { |
| 339 | if len(data) != 32 { |
| 340 | return fmt.Errorf("ristretto.Point should be 32 bytes; not %d", len(data)) |
| 341 | } |
| 342 | var buf [32]byte |
| 343 | copy(buf[:], data) |
| 344 | if !p.SetBytes(&buf) { |
| 345 | return errors.New("Buffer does not encode a ristretto.Point") |
| 346 | } |
| 347 | return nil |
| 348 | } |
| 349 | |
| 350 | // Implements encoding/BinaryMarshaler. Use BytesInto, if convenient, instead. |
| 351 | func (p *Point) MarshalBinary() ([]byte, error) { |
| 352 | var buf [32]byte |
| 353 | p.BytesInto(&buf) |
| 354 | return buf[:], nil |
| 355 | } |
| 356 | |
| 357 | func (p *Point) MarshalText() ([]byte, error) { |
| 358 | enc := base64.RawURLEncoding |
| 359 | var buf [32]byte |
| 360 | p.BytesInto(&buf) |
| 361 | ret := make([]byte, enc.EncodedLen(32)) |
| 362 | enc.Encode(ret, buf[:]) |
| 363 | return ret, nil |
| 364 | } |
| 365 | |
| 366 | func textToBuf(dst, src []byte) error { |
| 367 | var n int |
| 368 | var err error |
| 369 | if len(src) == 64 { |
| 370 | n, err = hex.Decode(dst, src) |
| 371 | if n == 32 && err == nil { |
| 372 | return nil |
| 373 | } |
| 374 | } |
| 375 | enc := base64.RawURLEncoding |
| 376 | n, err = enc.Decode(dst, src) |
| 377 | if err != nil { |
| 378 | return err |
| 379 | } |
| 380 | if n != 32 { |
| 381 | return fmt.Errorf("ristretto.Point should be 32 bytes; not %d", n) |
| 382 | } |
| 383 | return nil |
| 384 | } |
| 385 | |
| 386 | func (p *Point) UnmarshalText(txt []byte) error { |
| 387 | var buf [32]byte |
| 388 | err := textToBuf(buf[:], txt) |
| 389 | if err != nil { |
| 390 | return err |
| 391 | } |
| 392 | if !p.SetBytes(&buf) { |
| 393 | return errors.New("Buffer does not encode a ristretto.Point") |
| 394 | } |
| 395 | return nil |
| 396 | } |
| 397 | |
| 398 | func (p Point) String() string { |
| 399 | text, _ := p.MarshalText() |
| 400 | return string(text) |
| 401 | } |
| 402 | |
| 403 | func (p *Point) e() *edwards25519.ExtendedPoint { |
| 404 | return (*edwards25519.ExtendedPoint)(p) |
| 405 | } |
| 406 | |
| 407 | func (t *ScalarMultTable) t() *edwards25519.ScalarMultTable { |
| 408 | return (*edwards25519.ScalarMultTable)(t) |
| 409 | } |
| 410 | |
| 411 | // Fills the table for point p. |
| 412 | func (t *ScalarMultTable) Compute(p *Point) { |
| 413 | t.t().Compute(p.e()) |
| 414 | } |