Implement Lizard encoding/decoding (#826)

* Vendor lizard hash to curve from Signal

* Add invalid Lizard encoding test

* Added lizard details to readme and changelog

* Upgrade ristretto.sage to Python3

* Add lizard test vector generation to ristretto.sage

* Added map_to_curve and its inverse

* Use CtOption instead of bitmasks; other cleanup

* Add README to lizard folder

* Split map_to_curve into map_to_curve and map_to_curve_restricted; make its inverse return 16 elements

* Consolidate Ristretto Elligator functions into its own file
This commit is contained in:
Michael Rosenberg 2025-10-24 23:20:50 +02:00 committed by GitHub
parent c3a82a8a38
commit b76b924080
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 1681 additions and 427 deletions

View file

@ -0,0 +1,63 @@
# Go ed25519
Portions of curve25519-dalek were originally derived from Adam Langley's
Go ed25519 implementation, found at <https://github.com/agl/ed25519/>,
under the following licence:
```
Copyright (c) 2012 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```
# Lizard
The `src/lizard` directory was copied from [Signal's curve25519-dalek repo]( https://github.com/signalapp/curve25519-dalek/tree/7c6d34756355a3566a704da84dce7b1c039a6572). Its license is copied below
```
MIT License
Copyright (c) 2019 Bas Westerbaan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

View file

@ -5,6 +5,10 @@ major series.
## 5.x series
## Unreleased
* Add Lizard bytes-to-point injection for Ristretto. Gated under `lizard`.
## 5.0.0-pre.1
* Rename `Scalar::batch_invert` -> `Scalar::invert_batch` for consistency. Also make it no-alloc.

View file

@ -83,6 +83,7 @@ legacy_compatibility = []
group = ["dep:group", "rand_core"]
group-bits = ["group", "ff/bits"]
digest = ["dep:digest"]
lizard = ["digest"]
[target.'cfg(all(not(curve25519_dalek_backend = "fiat"), not(curve25519_dalek_backend = "serial"), target_arch = "x86_64"))'.dependencies]
curve25519-dalek-derive = "0.1"

View file

@ -26,40 +26,4 @@ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========================================================================
Portions of curve25519-dalek were originally derived from Adam Langley's
Go ed25519 implementation, found at <https://github.com/agl/ed25519/>,
under the following licence:
========================================================================
Copyright (c) 2012 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View file

@ -57,6 +57,7 @@ curve25519-dalek = ">= 5.0, < 5.2"
| `legacy_compatibility`| | Enables `Scalar::from_bits`, which allows the user to build unreduced scalars whose arithmetic is broken. Do not use this unless you know what you're doing. |
| `group` | | Enables external `group` and `ff` crate traits. |
| `group-bits` | | Enables `group` and impls `ff::PrimeFieldBits` for `Scalar`. |
| `lizard` | | Enables the [Lizard](src/lizard/README.md) bytestring-to-point injection for `RistrettoPoint`. Specifically enables the methods `lizard_encode` and `lizard_decode`. |
To disable the default features when using `curve25519-dalek` as a dependency,
add `default-features = false` to the dependency in your `Cargo.toml`. To

View file

@ -17,7 +17,7 @@ impl std::fmt::Display for DalekBits {
DalekBits::Dalek32 => "32",
DalekBits::Dalek64 => "64",
};
write!(f, "{}", w_bits)
write!(f, "{w_bits}")
}
}

View file

@ -98,6 +98,12 @@ impl ConstantTimeEq for FieldElement {
}
}
impl Default for FieldElement {
fn default() -> Self {
FieldElement::ZERO
}
}
impl FieldElement {
/// Load a `FieldElement` from 64 bytes, by reducing modulo q.
#[cfg(feature = "digest")]

View file

@ -90,6 +90,9 @@ pub(crate) mod backend;
// Generic code for window lookups
pub(crate) mod window;
#[cfg(feature = "lizard")]
pub mod lizard;
pub use crate::{
edwards::EdwardsPoint, montgomery::MontgomeryPoint, ristretto::RistrettoPoint, scalar::Scalar,
};

View file

@ -0,0 +1,515 @@
# Computing Preimages of Ristretto255 Points Under the Elligator2 Map
# Introduction
The [Elligator2][elligator] map provides a way to map field elements to elliptic curve points with a nearly uniform distribution. When adapted for [Ristretto255][ristretto], it maps elements of the field $\mathbb{F}_p$ (where $p = 2^{255} - 19$) to points in the Ristretto255 group. This mapping is not injective; each Ristretto255 point can be the image of up to eight distinct field elements.
Some use cases, however, require an injective map into the Ristretto group with an easy-to-compute inverse. This is handy if, e.g., we want to encrypt data with the [ElGamal](https://en.wikipedia.org/wiki/ElGamal_encryption) encryption scheme, where plaintexts are curve points. This injection is precisely what the ["Lizard"][lizard] encoding provides.
In this document, we describe the Lizard encoding/decoding algorithms. Along the way we will describe an efficient method for computing preimages of the Elligator2 map. These algorithms are implemented in `src/lizard/` in this repo.
# Lizard
The Lizard encoding is an injective map into the Ristretto255 group $\mathcal{R}$ built on the Elligator2 map, $E_2$.
## Encoding: Make Elligator2 an injection
As mentioned above, $E_2$ is not injective and thus cannot work directly as an encoding function.
Instead we create an injective function from $E_2$ by "tagging" each input $x$ so it is distinguished among the other inverses of $E_2(x)$. This requires restricting the map's domain: rather than mapping $\mathbb{F} \to \mathcal{R}$, we define a map $\lbrace 0,1 \rbrace^{128} \to \mathcal{R}$ (i.e., half the input length), as follows:
1. Given bitstring $b \in \lbrace 0,1 \rbrace^{128}$, compute its hash $h = \mathsf{H}(b)$ where $\mathsf{H}$ is a hash function with a 32-byte digest.
2. Let `s` be the 32-byte value `h[0:8] || b || h[24:32]`.
3. Clear the least significant bit: `s[0] &= 254`. This is done so that the field element represented by `s` is "positive" (defined in next section).
4. Clear the most significant two bits: `s[31] &= 63`. This is done so that the field element represented by `s` does not exceed $p$.
5. Interpret `s` as a field element (little endian), and output $E_2(s)$
## Decoding: Invert the injection
The tag allows us to decode points $P \in \mathcal{R}$ as follows:
1. Compute the set of preimages $E_2^{-1}(P)$ using the procedure described in the rest of this document. This gives us a set of up to 8 scalars that are candidates to be the correct inverse.
2. For each candidate scalar, check whether it adheres to the above form. Namely check that it is positive and has byte representation `h[0:8] || b || h[24:32]`, where $h = \mathsf{H}(b)$, and the appropriate bits are cleared.
3. If such a candidate is found, this is the decoded value.
The above procedures are exactly what the `lizard_encode` and `lizard_decode` functions do in `src/lizard/lizard_ristretto.rs`.
## Security argument
It is not a-priori clear that the function described is an injection.
We repeat [Bas Westerbaan's argument](https://github.com/bwesterb/go-ristretto/blob/7c80df9e61a54045aedb2ccad99d1e636a4b4c90/ristretto.go#L224) for why this method produces an injection with overwhelming probability:
> There are some (and with high probability at most 80) inputs to SetLizard() which cannot be decoded. The chance that you hit such an input is around 1 in 2^122.
> In Lizard there are $256 - 128 - 3 = 125$ check bits to pick out the right preimage among at most eight. Conservatively assuming there are seven other preimages, the chance that one of them passes the check as well is given by:
> $$
\begin{align}
1 - (1 - 2^{-125})^7
&= 7\cdot 2^{-125} + 21\cdot 2^{-250} - ...
\\\\&\approx 2^{-125 - 2\log(7)}
\\\\&= 2^{-122.192\ldots}
\end{align}
$$
> Presuming a random hash function, the number of "bad" inputs is binomially distributed with $n=2^{128}$ and $p=2^{-122.192}\ldots$ For such large $n$, the Poisson distribution with $\lambda=np=56$ is a very good approximation. In fact: the cumulative distribution function (CDF) of the Poission distribution is larger than that of the binomial distribution for $k > \lambda$.[^1] The value of the former on $k=80$ is larger than 0.999 and so with a probability of 99.9%, there are fewer than 80 bad inputs.
# Inverting $E_2$
Methods for efficiently implementing the Elligator2 map $E_2$ have been carefully documented on the [Ristretto255][ristretto] website, and using this the implementation of Lizard *encoding* is straightforward. Lizard *decoding*, on the other hand requires efficiently inverting $E_2$ and we describe that process here.
## Background and Notation
The computations will involve a family of related curves all defined over the prime field of order $p = 2^{255} - 19$ which we denote by $\mathbb{F}$. We will adopt the definition of [Decaf][decaf] and define an element of $\mathbb{F}$ to be *positive* if the low bit of its least positive representative is set.
### Fundamental Curves
**The Twisted Edwards Curve $\mathcal{E}$.**
Much of our work will take place in the Twisted Edwards Curve $\mathcal{E}_{a,d}$ given by
$$
ax^2+y^2=1+dx^2y^2.
$$
where $a = -1$ and $d =-121665/121666$. In what follows we will simply denote this curve by $\mathcal{E}$, but we will refer to $a$ and $d$ explicitly when it helps clarify the relationships between curves and dispel any magic behind the apparently magic numbers.
The addition law on $\mathcal{E}$ is given by $(x_1, y_1) + (x_2,y_2) = (x_3,y_3)$ where:
$$
x_3 = \frac{x_1y_2 + x_2y_1}{1 + d x_1 y_1 x_2 y_2}, \quad y_3 = \frac{ y_1 y_2 - a x_1 x_2}{1 - d x_1 y_1 x_2 y_2}.
$$
The 4-torsion subgroup will be of particular interest. It is cyclic and consists of the points:
$$
\mathcal{E}[4] = \lbrace (0,1), (1,0), (0,-1), (-1, 0) \rbrace.
$$
The size of $\mathcal{E}$ is $|\mathcal{E}| = 8\ell$ where $\ell = 2^{252}+27742317777372353535851937790883648493$ is prime.
**The Jacobi Quartic $\mathcal{J}$.**
We also consider the Jacobi quartic $\mathcal{J}_{e,A}$ given by
$$
t^2=es^4+2As^2+1,
$$
where $e = (-a)^2 = 1$ and $A = -a - 2ad/(a-d) = 243329$.
We denote this curve by $\mathcal{J}$.
$\mathcal{J}$ is 2-isogenous to $\mathcal{E}$ through the mapping $\theta:\mathcal{J} \rightarrow \mathcal{E}$:
$$
\theta(s,t) = \left(\frac{1}{\sqrt{-d-1}}\cdot\frac{2s}{t}, \frac{1-s^2}{1+s^2} \right).
$$
The addition law on $\mathcal{J}$ is given by $(s_1, t_1)+(s_2, t_2) = (s_3, t_3)$ where
$$
s_3 = \frac{s_1 t_2 + s_2 t_1}{1 - e s_{1}^2 s_{2}^2},\quad t_3 = \frac{(t_1 t_2 + 2A s_1 s_2)(1 + e s_1^2s_2^2) + 2e s_1 s_2 (s_1^2 + s_2^2)}{(1 - e s_1^2 s_2^2)^2}
$$
$\mathcal{J}$ has full 2-torsion, that is, $|\mathcal{J}[2]| = 4$ and given a point $(s,t)\in\mathcal{J}$, its coset for the 2-torsion subgroup of $\mathcal{J}$ is given by
$$
(s,t) + \mathcal{J}[2] = \lbrace (s,t), (-s,-t), (1/as, -t/as^2), (-1/as, t/as^2) \rbrace
$$
The size of $\mathcal{J}$ is $|\mathcal{J}| = 8\ell$.
**The Montgomery Curve $\mathcal{M}$.**
Although we will not use it in this document, it is convenient to know that $\mathcal{E}$ and $\mathcal{J}$ are closely related to Curve25519, the Montgomery curve given by the equation
$$
y^{2}=x^{3}+486662x^{2}+x = x^3 + 2\frac{a+d}{a - d}x^2 + x
$$
In particular $\mathcal{M}$ is birationally equivalent to $\mathcal{E}$ and is 2-isogenous to $\mathcal{J}$.
The size of $\mathcal{M}$ is $|\mathcal{M}| = 8\ell$
### Ristretto
The Ristretto255 group is the group $\mathcal{R} = [2]\mathcal{E}/\mathcal{E}[4]$ of prime order $\ell$. Each element of $\mathcal{R}$ can be represented by an even point $(x,y)\in\mathcal{E}_{a,d}$. Writing the four-element coset out in full:
$$
(x,y) + \mathcal{E}_{a,d}[4] = \left\lbrace (x,y), (\frac{y}{\sqrt{a}}, -x\sqrt{a}), (-x,-y), (\frac{-y}{\sqrt{a}}, x\sqrt{a}) \right\rbrace.
$$
With our parameter choice of $a = -1$ this simplifies to
$$
\lbrace (x,y), (-x,-y), (\mathrm{i} y, \mathrm{i} x), (-\mathrm{i} y, -\mathrm{i} x) \rbrace,
$$
where $\mathrm{i} = \sqrt{-1}$ is the imaginary unit in $\mathbb{F}$.
## The Components of Elligator2
$E_2$ is built from four functions:
1. A map from field elements to a Jacobi quartic: $e: \mathbb{F} \rightarrow \mathcal{J}$.
1. The quotient map: $q_\mathcal{J}: \mathcal{J} \rightarrow \mathcal{J}/\mathcal{J}[2]$
1. A 2-isogeny from the Jacobi quartic to the even points on the Edwards curve: $\theta: \mathcal{J} \rightarrow [2]\mathcal{E}$. Note that we only know that the image of $\theta$ consists of even points because the torsion group $\mathcal{E}[8]$ is cyclic. See discussion below.
1. The quotient map into the Ristretto group: $q_\mathcal{E}: [2]\mathcal{E}/\mathcal{E}[2] \rightarrow \mathcal{R}$, where $P \mapsto P + \mathcal{E}[4]/\mathcal{E}[2]$.
Now since $\mathsf{ker}(\theta) \leqslant \mathcal{J}[2]$, [the Decaf paper][decaf] shows that the map
$$
\hat{\theta}: \frac{\mathcal{J}}{\mathcal{J}[2]} \rightarrow \frac{\theta(\mathcal{J})}{\theta(\mathcal{J}[2])} = \frac{[2]\mathcal{E}}{\mathcal{E}[2]}, \qquad P + \mathcal{J}[2] \mapsto \theta(P) + \mathcal{E}[2]
$$
<div id="eq-reduced-theta" align="right">(1)</div>
is an isomorphism.
The full map is $E_2 = q_\mathcal{E} \circ \hat{\theta} \circ q_\mathcal{J} \circ e$. Our goal is to compute the preimage set $E_2^{-1}(P)$ for a given Ristretto point $P \in \mathcal{R}$.
Since $q_\mathcal{E}$ is 2-to-1, $\hat{\theta}$ is 1-to-1, and $q_\mathcal{J}$ is 4-to-1, we expect to find $4 \times 2 = 8$ preimages on the Jacobi quartic $\mathcal{J}$. Each of these 8 points on $\mathcal{J}$ will then correspond to two field elements, one positive and one negative, via the inverse of $e$ (thus there is a unique corresponding positive field element via $e^{-1}$). This section explains how to find these 16 field elements.
We now describe how to invert each of these components before presenting an efficient algorithm to compute the full inverse of $E_2$.
### The Quotient Maps and their Inverses
Given a point $(x,y) + \mathcal{E}[2] \in \mathcal{E}/\mathcal{E}[2]$, $q_\mathcal{E}$ maps it to its coset in the quotient group in $\mathcal{E}/\mathcal{E}[4]$:
$$
q_\mathcal{E}(\lbrace (x,y), (-x,-y)\rbrace) = \lbrace (x,y), (-x,-y), (\mathrm{i} y, \mathrm{i} x), (-\mathrm{i} y, -\mathrm{i} x) \rbrace.
$$
From which we can see it is a 2-to-1 map, since $\lbrace (x,y), (-x,-y) \rbrace$ and $\lbrace (\mathrm{i} y, \mathrm{i} x), (-\mathrm{i} y, -\mathrm{i} x) \rbrace$ map to the same point.
When its domain is restricted to the even points $[2]\mathcal{E}/\mathcal{E}[2]$ we see that $|[2]\mathcal{E}/\mathcal{E}[2]| = 2\ell$ so its range must have size $\ell$ - the size of $\mathcal{R}$. Thus $q_\mathcal{E}$ maps onto $\mathcal{R}$. $q$ is also simple to invert:
$$
q_\mathcal{E}^{-1}((x,y) + \mathcal{E}[4]) = \left\lbrace \lbrace(x,y), (-x,-y)\rbrace, \lbrace(\mathrm{i} y, \mathrm{i} x), (-\mathrm{i} y, -\mathrm{i} x)\rbrace \right\rbrace.
$$
Note the extra braces here. $q_\mathcal{E}^{-1}(P)$ contains two elements of $\mathcal{E}/\mathcal{E}[2]$ and each of these elements is a coset of size two.
This formula is valid for all points in $\mathcal{E}/\mathcal{E}[4]$, but for points that are not in $\mathcal{R} = [2]\mathcal{E}/\mathcal{E}[4]$ their preimages will not be in the range of $\hat{\theta}$, described next, and we will not be able to continue the inversion of $E_2$. This is expected since these are not validly encoded points.
The quotient map $q_\mathcal{J}$ is also simple to describe and invert
$$
q_\mathcal{J}((s,t)) = (s,t) + \mathcal{J}[2] = \lbrace (s,t), (-s,-t), (-1/s, t/s^2), (1/s, -t/s^2) \rbrace.
$$
So
$$
q_\mathcal{J}^{-1}((s,t) + \mathcal{J}[2]) = \lbrace (s,t), (-s,-t), (-1/s, t/s^2), (1/s, -t/s^2) \rbrace.
$$
### The Isogeny $\theta$ and its Inverse
The Elligator2 construction for Ristretto255 uses the Jacobi quartic curve $\mathcal{J}$ defined by the equation $t^2 = s^4 + A s^2 + 1$, which is 2-isogenous to our twisted Edwards curve $\mathcal{E}$. The 2-isogeny $\theta: \mathcal{J} \rightarrow \mathcal{E}$ is given by:
$$
\theta(s,t) = (x,y) = \left( \frac{2s}{t\sqrt{c}}, \frac{1-s^2}{1+s^2} \right)
$$
where for a twisted Edwards curve $ax^2+y^2=1+dx^2y^2$, the constant $c = a-d$. For Ristretto255, $a=-1$, so $c = -1-d$. Note that $\theta(s, t) = \theta(-s, -t)$, so this map is inherently 2-to-1 from the points on $\mathcal{J}$ to points on $\mathcal{E}$.
#### The Projected Map, $\hat{\theta}$
By a special case of Tate's Isogeny Theorem,[^2] since the isogenous curves $\mathcal{J}$ and $\mathcal{E}$ are both defined over $\mathbb{F}$, they have the same number of rational points, i.e., they have the same number of points in $\mathbb{F}$. Since $\theta$ is 2-to-1, this means that $\theta(\mathcal{J})$ is a subgroup of $\mathcal{E}$ of index 2. Since $\mathcal{E}$ is cyclic, $[2]\mathcal{E}$ is the only index-2 subgroup and we see that $\theta(\mathcal{J}) = [2]\mathcal{E}$.
We also see that because 2-torsion points must map to 2-torsion points we have $\theta(\mathcal{J}[2]) \leqslant \mathcal{E}[2]$. Also, since $\mathcal{J}[2]$ has 4 points and $|\mathsf{ker(\theta)}| = 2$, at least one point in $\mathcal{J}[2]$ does not map to zero and $|\theta(\mathcal{J}(2))| \geq 2$. But $|\mathcal{E}[2]| = 2$ so it follows that $\theta(\mathcal{J}[2]) = \mathcal{E}[2]$.
Thus we are justified in talking about the projected map $\hat{\theta}$ defined in [Equation 1](#eq-reduced-theta).
#### Inverting $\theta$ (and $\hat{\theta}$)
Given a point $(x,y) \in \mathcal{E}$, we can invert $\theta$ to find its two preimages on $\mathcal{J}$. From the $y$-coordinate, we have:
$$
y = \frac{1-s^2}{1+s^2} \implies s^2 = \frac{1-y}{1+y}
$$
This gives two possible values for $s$, which we denote $s_0$ and $-s_0$. From the $x$-coordinate, we can then find the corresponding $t$ value:
$$
x = \frac{2s}{t\sqrt{c}} \implies t = \frac{2s}{x\sqrt{c}}
$$
Therefore, for each Edwards point $(x,y)$:
$$
\theta^{-1}((x,y)) = \lbrace (s_0,t_0), (-s_0, -t_0) \rbrace
$$
where $s_0 = \sqrt{\frac{1-y}{1+y}}$ and $t_0 = \frac{2s_0}{x\sqrt{c}}$.
Note that when writing an Edwards point in projective coordinates, $X:Y:Z$ this becomes
$$
s_0 = \sqrt{\frac{Z-Y}{Z+Y}},\qquad t_0 = \frac{2Z}{X\sqrt{c}}\sqrt{\frac{Z-Y}{Z+Y}}
$$
These formulas allow us to write the inverse for $\hat{\theta}$ as well. Note that an equivalence class in $[2]\mathcal{E}/\mathcal{E}[2]$ is given by
$$
[X:Y:Z] + \mathcal{E}[2] = \left\lbrace [X:Y:Z], [-X:-Y:Z]\right\rbrace
$$
So
$$
\hat{\theta}^{-1}(\lbrace [X:Y:Z], [-X:-Y:Z] \rbrace) = \left\lbrace (s_0, t_0), (-s_0, -t_0), \left(\frac{1}{s_0}, -\frac{t_0}{s_0^2}\right), \left(-\frac{1}{s_0}, \frac{t_0}{s_0^2}\right) \right\rbrace = (s_0,t_0) + \mathcal{J}[2]
$$
Note that this inverse will exist if and only if $[X:Y:Z] \in [2]\mathcal{E}$.
### $e$ and its Inverse
<div id="subsec-e-and-inverse"></div>
The Elligator2 map from $\mathbb{F}$ to $\mathcal{J}$ is computed as follows. On input $r_0$, let $r = \mathrm{i}r_0^2$—either $0$ or a non-residue. Then compute
$$
\begin{align}
(s,t) &= \left( + \sqrt{ \frac{ (r+1)(d - 1)(d + 1) }{ (d r +1)(r + d) } } , \frac{ (r-1)(d - 1)^2 }{ (d r + 1)(r + d) } - 1 \right)
\end{align}
$$
or
$$
\begin{align}
(s,t) &= \left( - \sqrt{ \frac{ r(r+1)(d - 1)(d + 1) }{ (d r + 1)(r + d) } } , \frac{ -r(r-1)(-1 + d)^2 }{ (d r + 1)(r + d) } - 1 \right)
\end{align}
$$
depending on which square root exists, preferring the second when $r = 0$ and both are square.
#### The case $s > 0$
We want to invert this and will begin with the first case, where $s > 0$. First note that
$$
\frac{t+1}{s^2} = \frac{d-1}{d+1}\frac{r-1}{r+1}
$$
<div id="eq-a-over-s2" align="right">(2)</div>
We introduce the value $\alpha = \frac{d+1}{d-1}(t+1)$, which is denoted `a` in the source code. This gives
$$
\frac{\alpha}{s^2} = \frac{r-1}{r+1}
$$
from which we solve for $r$:
$$
r = \frac{s^2 + \alpha}{s^2 - \alpha}
$$
Thus our inverse will be
$$
r_0 = \pm\sqrt{-\mathrm{i}\frac{s^2 + \alpha}{s^2 - \alpha}}
$$
<div id="eq-r0case1" align="right">(3)</div>
#### The case $s\leq 0$
When considering the second case, $s \leq 0$, note that [Equation 2](#eq-a-over-s2) just negates the right hand side
$$
\frac{t+1}{s^2} = -\frac{d-1}{d+1}\frac{r-1}{r+1}
$$
leading to the formula
$$
r = \frac{s^2 - \alpha}{s^2 + \alpha}
$$
Thus our inverse will be
$$
r_0 = \pm\sqrt{-\mathrm{i}\frac{s^2 - \alpha}{s^2 + \alpha}}
$$
<div id="eq-r0case2" align="right">(4)</div>
# Algorithm for Computing All 16 Preimages of a Point
We can combine these computations to invert $E_2$.
First, when inverting $q_\mathcal{E}$, observe that if a point $P\in\mathcal{R}$ has a representative with projective coordinates $[X:Y:Z]$ then its inverse under $q_\mathcal{E}$ is given by
$$
q_\mathcal{E}^{-1}(P) = \lbrace \lbrace [X:Y:Z], [-X:-Y:Z] \rbrace, \lbrace [Y:X:\mathrm{i}Z], [-Y:-X:\mathrm{i}Z] \rbrace \rbrace.
$$
Above we showed how, given a point $X:Y:Z \in [2]\mathcal{E}/\mathcal{E}[2]$ we can compute its preimage
$$
\hat{\theta}^{-1}([X:Y:Z] + \mathcal{E}[2]) = \left\lbrace (s_0, t_0), (-s_0, -t_0), \left(\frac{1}{s_0}, -\frac{t_0}{s_0^2}\right), \left(-\frac{1}{s_0}, \frac{t_0}{s_0^2}\right) \right\rbrace
$$
We can repeat this process to compute preimage of $[Y:X:\mathrm{i}Z] + \mathcal{E}[2]$, the other point in $q_\mathcal{E}^{-1}(P)$:
$$
\hat{\theta}^{-1}([Y:X:\mathrm{i}Z] + \mathcal{E}[2]) = \left\lbrace (s_2, t_2), (-s_2, -t_2), \left(\frac{1}{s_2}, -\frac{t_2}{s_2^2}\right), \left(-\frac{1}{s_2}, \frac{t_2}{s_2^2}\right) \right\rbrace
$$
This already yields an algorithm to compute inverses of $E_2$ and complete the Lizard decoding, but we can make some significant optimizations.
## Step 1: Find Four Non-Dual Jacobi Points That Map to a Ristretto Point
<div id="subsec-step1"></div>
Based on the calculations above, once we compute the the four points $(s_i, t_i)$ as follows
$$
\begin{align}
s_0 = \sqrt{\frac{Z-Y}{Z+Y}},&\quad& t_0 = \frac{2Z}{X\sqrt{c}}\sqrt{\frac{Z-Y}{Z+Y}} \\
s_1 = \frac{1}{s_0},&\quad& t_1 = -\frac{t_0}{s_0^2} \\
s_2 = \sqrt{\frac{\mathrm{i}Z-X}{\mathrm{i}Z+X}},&\quad& t_0 = \frac{2\mathrm{i}Z}{Y\sqrt{c}}\sqrt{\frac{\mathrm{i}Z-X}{\mathrm{i}Z+X}} \\
s_3 = \frac{1}{s_2},&\quad& t_3 = -\frac{t_2}{s_2^2} \\
\end{align}
$$
we easily get all eight preimages of the Ristretto point $[X:Y:Z] + \mathcal{E}[4]$ by taking their "dual" points, where the *dual* of $(s,t)$ is $(-s,-t)$:
$\lbrace \pm(s_i, t_i) \rbrace$.
This computation is performed by the function `to_jacobi_quartic_ristretto` in `src/lizard/lizard_ristretto.rs`. We describe that computation now.
### Sharing Computation
We can compute $s_0$ and $s_1$ more efficiently together by precomputing $1/\sqrt{Z^2 - Y^2}$, then multiplying by $(Z-Y)$ and $(Z+Y)$ respectively. Similarly we can compute $s_2$ and $s_3$ together by precomputing $1/\sqrt{X^2 + Z^2}$ then multiplying by $(\mathrm{i}Z-X)$ and $(\mathrm{i}Z+X)$ respectively.
It turns out that we can perform both of these precomputations while only computing one square root. In particular, compute the following value:
$$
\gamma = \frac{1}{\sqrt{Y^4X^2(Z^2-Y^2)}}
$$
Then we can easily compute $s_0$ and $s_1$ with inexpensive field operations:
$$
s_0 = \gamma Y^2 (Z-Y) X, \quad s_1 = \gamma Y^2 (Z+Y) X
$$
Now $\gamma Y^2 = 1/\sqrt{X^2(Z^2 - Y^2)}$ and, when we are computing $s_2, s_3$ the analog of this value is $-i/\sqrt{Y^2(X^2 + Z^2)}$. So we can compute
$$
\begin{align}
\sqrt{\frac{-1}{Y^2(X^2 + Z^2)}} &=& \sqrt{\frac{Z^2 - Y^2}{(X^2 + Z^2)(Y^2 - Z^2)}} \\
&=& \sqrt{\frac{Z^2 - Y^2}{X^2Y^2 + dX^2Y^2}} \\
&=& \frac{1}{\sqrt{d+1}}\sqrt{\frac{Z^2-Y^2}{X^2Y^2}} \\
&=& \frac{1}{\sqrt{d+1}} \gamma (Z^2 - Y^2)
\end{align}
$$
Where the equality in the second line comes from using the curve equation for $\mathcal{E}$: $Y^2Z^2 - X^2Z^2 = Z^4 + dX^2Y^2$. The quantity $1/\sqrt{d+1}$ is a constant that can be precomputed, so $\sqrt{-1/(Y^2(X^2 + Z^2))}$ —and hence $(s_2,t_2)$ and $(s_3,t_3)$—can be computed from $\gamma$ without computing an additional square root.
### Step by Step Through the Rust Implementation
With that background, we can understand the code in `src/lizard/lizard_ristretto.rs`. The following steps can be found in the `RistrettoPoint::to_jacobi_quartic_ristretto()` function:
1. $\gamma \leftarrow 1/\sqrt{Y^4X^2(Z^2 - Y^2)}$
1. $D \leftarrow \gamma Y^2$
1. $\mathsf{s\\_over\\_x} = D(Z-Y)$, $\mathsf{sp\\_over\\_xp} = D(Z+Y)$
1. $s_0 = \mathsf{s\\_over\\_x}\cdot X$, $s_1 = \mathsf{sp\\_over\\_xp}\cdot X$. Note that
$$
s_0 = D(Z-Y)X = \frac{X(Z-Y)}{\sqrt{X^2(Z^2 - Y^2)}} = \sqrt{\frac{Z-Y}{Z+Y}}
$$
as required.
5. $\mathsf{tmp} \leftarrow \frac{-2}{\sqrt{-d-1}}Z$
5. $t_0 \leftarrow \mathsf{tmp}\cdot \mathsf{s\\_over\\_x}$, $t_1 \leftarrow \mathsf{tmp}\cdot \mathsf{sp\\_over\\_xp}$
5. $(s_0,t_0)$ and $(-s_0, -t_0)$ are preimages of $X:Y:Z$ while $(s_1,t_1)$ and $(-s_1,-t_1)$ are preimages of $-X:-Y:Z$.
5. $D \leftarrow (Z^2 - Y^2)\gamma \cdot -1/\sqrt{-d-1}$ (This equals $\frac{1}{\sqrt{-d-1}}\sqrt{-\frac{Z^2 - Y^2}{Y^4X^2}}$)
5. $\mathsf{s\\_over\\_y} \gets D(\mathrm{i}Z - X)$
5. $\mathsf{sp\\_over\\_yp} \leftarrow D (\mathrm{i}Z + X)$
5. $s_2 \leftarrow \mathsf{s\\_over\\_y} \cdot Y$, $s_3 \leftarrow \mathsf{sp\\_over\\_yp} \cdot Y$
5. $\mathsf{tmp} \leftarrow \frac{-2}{\sqrt{-d-1}}\mathrm{i}Z$
5. $t_2 \leftarrow \mathsf{tmp}\cdot \mathsf{s\\_over\\_y}$, $t_3 \leftarrow \mathsf{tmp}\cdot \mathsf{sp\\_over\\_yp}$
5. $(s_2,t_2)$ and $(-s_2, -t_2)$ are preimages of $Y:X:\mathrm{i}Z$ while $(s_3,t_3)$ and $(-s_3,-t_3)$ are preimages of $-Y:-X:\mathrm{i}Z$.
Altogether this gives us eight candidate Jacobi Quartic points:
$$
(s_0, t_0),(s_1, t_1),(s_2, t_2),(s_3, t_3),
(-s_0, -t_0),(-s_1, -t_1),(-s_2, -t_2),(-s_3, -t_3)
$$
Note the `to_jacobi_quartic_ristretto()` function only returns the first 4 points. The remaining ones are derived in `RistrettoPoint::elligator_ristretto_flavor_inverse()` in the same file.
The conditional assignments in `to_jacobi_quartic_ristretto()` are explained below.
### Handling Special Cases
The formulas above assume non-zero denominators. The special cases occur when the input point is a 2-torsion or 4-torsion point.
If the input point is the identity element, its representatives are $(0,1)$, $(0,-1)$, $(\mathrm{i}, 0)$, and $(-\mathrm{i}, 0)$.
1. For $(0,1)$, we have $y=1$, so $s^2 = 0 \implies s=0$. This gives the Jacobi point $(0,1)$.
1. For $(0,-1)$, we have $y=-1$, so $s^2$ is undefined (division by zero). However, this 1. corresponds to $s^2 \to \infty$. In the code we simply repeat the point $(0,1)$ in this 1. This repetition is harmless since this point has no preimage under the Elligator2 map from $\mathbb{F}$ to $\mathcal{J}$ and cannot correspond to a Lizard encoded bitstring.
1. For $(\mathrm{i}, 0)$, we have $y=0$, so $s^2=1 \implies s=\pm 1$. The preimages are $(\pm 1, \frac{2\mathrm{i}}{\sqrt{-d-1}})$.
1. For $(-\mathrm{i}, 0)$, we have $y=0$, so $s^2=1 \implies s=\pm 1$. The preimages are $(\pm 1, \mp\frac{2\mathrm{i}}{\sqrt{-d-1}}))$.
## Step 3: Compute the 16 Field Element Preimages
The computation of $e^{-1}$ [described above](#subsec-e-and-inverse) required breaking the computation into two cases. To facilitate performing these computations efficiently in constant time, we perform both computations at once. This code can be found in `src/lizard/jacobi_quartic.rs` in `JacbobiPoint::e_inv()`.
We begin by computing the value
$$
y = \frac{1}{\sqrt{\mathrm{i} (s^4 - \alpha^2)}}
$$
Note that
1. $\frac{1}{\mathrm{i} (s^4 - \alpha^2)}$ is a quadratic residue if and only if $(s^4 - \alpha^2)$ is not a quadratic residue.
1. $s^4 - \alpha^2$ is not a quadratic residue if and only if exactly one of $s^2 - \alpha$ and $s^2 + \alpha$ is a quadratic residue.
1. exactly one of $s^2 - \alpha$ and $s^2 + \alpha$ is a quadratic residue if and only if both $\frac{s^2 - \alpha}{s^2 + \alpha}$ and $\frac{s^2 + \alpha}{s^2 - \alpha}$ are non-residues.
1. Both $\frac{s^2 - \alpha}{s^2 + \alpha}$ and $\frac{s^2 + \alpha}{s^2 - \alpha}$ are non-residues if and only if $\sqrt{-\mathrm{i}\frac{s^2 + \alpha}{s^2 - \alpha}}$ and $\sqrt{-\mathrm{i}\frac{s^2 - \alpha}{s^2 + \alpha}}$ exist.
Hence we see that $(s,t)$ has a preimage if and only if $y$, as defined above, exists.
With $y$ computed we can now compute the final preimage. Let $\mathsf{sgn}(s)$ denote the sign function. Then we can consolidate Equations [3](#eq-r0case1) and [4](#eq-r0case2) into
$$
r_0 = \pm(\alpha + \mathsf{sgn}(s)s^2) y
$$
### Relation to the Formulas in Decaf
These computations can also be seen in [Decaf][decaf], which also defines the map $e: \mathbb{F} \rightarrow \mathcal{J}$, but we need to clarify an important difference in notation. In that work, they use variables $a$ and $d$ as parameters for a different, but isogenous, twisted Edwards curve. If we let $\hat{a}$ and $\hat{d}$ denote the Edwards curve parameters from Decaf we have the relations
$$
\hat{a} = -a, \quad \hat{d} = \frac{ad}{a-d}
$$
Note that in this notation we have
$$
2\hat{d} - \hat{a} =
\frac{d-1}{d+1}
$$
hence the formula given in for the inverse of $e$ can be rewritten
$$
nr_0^2 = r = \frac{(2\hat{d} - \hat{a})s^2 + c(t+1)}{(2\hat{d} - \hat{a})s^2 - c(t+1)} = \frac{cs^2 + (t+1)\frac{d+1}{d-1}}{cs^2 - (t+1)\frac{d+1}{d-1}}
$$
where $c = \mathsf{sgn}(s)$. There is another detail we need to take care of. The map in Decaf is defined parameterized by a non-square $n\in\mathbb{F}_{p}$. We take $n = \sqrt{-1}$ as the non-residue parameter.
You can see this choice of $n$, in the implementation of `RistrettoPoint::elligator_ristretto_flavor()`.
[^1]: Anderson, T. W. and Samuels, S. M., Some Inequalities Among Binomial and Poisson Probabilities _Proc. Fifth Berkeley Symp. on Math. Statist. and Prob._, Vol. 1. Univ. of Calif. Press (1967).
[^2]: Tate, J. Endomorphisms of abelian varieties over finite fields. _Invent Math_ 2, 134–144 (1966). https://doi.org/10.1007/BF01404549 [[pdf](https://pazuki.perso.math.cnrs.fr/index_fichiers/Tate66.pdf)]
[elligator]: https://elligator.org/
[ristretto]: https://ristretto.group/
[lizard]: https://arxiv.org/abs/1911.02674
[decaf]: https://eprint.iacr.org/2015/673

View file

@ -0,0 +1,71 @@
//! Helper functions for use with Lizard
#![allow(non_snake_case)]
use subtle::{ConditionallyNegatable, ConditionallySelectable, ConstantTimeEq, CtOption};
use super::lizard_constants;
use crate::constants;
use crate::field::FieldElement;
/// Represents a point (s,t) on the the Jacobi quartic associated
/// to the Edwards curve.
#[derive(Copy, Clone)]
#[allow(missing_docs)]
pub struct JacobiPoint {
pub S: FieldElement,
pub T: FieldElement,
}
impl JacobiPoint {
/// Elligator2 is defined in two steps: first a function `e` maps a field element `x`
/// to a point on the Jacobi quartic associated to the Edwards curve.
/// Then this point is mapped to a point on the Edwards curve.
/// Note `e` maps `x` and `-x` to the same point.
/// This function computes a positive field element that is mapped by `e` to a given point,
/// if it exists. The other inverse is the negative of the return value.
pub(crate) fn e_inv_positive(&self) -> CtOption<FieldElement> {
let mut out = FieldElement::ZERO;
// Special case: s = 0. If s is zero, either t = 1 or t = -1.
// If t=1, then sqrt(i*d) is the preimage. Otherwise it's 0.
let s_is_zero = self.S.is_zero();
let t_equals_one = self.T.ct_eq(&FieldElement::ONE);
out.conditional_assign(&lizard_constants::SQRT_ID, t_equals_one);
let mut is_defined = s_is_zero;
let mut done = s_is_zero;
// a := (t+1) (d+1)/(d-1)
let a = &(&self.T + &FieldElement::ONE) * &lizard_constants::DP1_OVER_DM1;
let a2 = a.square();
// y := 1/sqrt(i (s^4 - a^2)).
let s2 = self.S.square();
let s4 = s2.square();
let invSqY = &(&s4 - &a2) * &constants::SQRT_M1;
// There is no preimage if the square root of i*(s^4-a^2) does not exist.
let (sq, y) = invSqY.invsqrt();
is_defined |= sq;
done |= !sq;
// x := (a + sign(s)*s^2) y
let mut pms2 = s2;
pms2.conditional_negate(self.S.is_negative());
let mut x = &(&a + &pms2) * &y;
// Always pick the positive solution
let x_is_negative = x.is_negative();
x.conditional_negate(x_is_negative);
out.conditional_assign(&x, !done);
CtOption::new(out, is_defined)
}
pub(crate) fn dual(&self) -> JacobiPoint {
JacobiPoint {
S: -(&self.S),
T: -(&self.T),
}
}
}

View file

@ -0,0 +1,49 @@
//! Constants for use in Lizard
//!
//! Could be moved into backend/serial/u??/constants.rs
#[cfg(curve25519_dalek_bits = "64")]
pub(crate) use super::u64_constants::*;
#[cfg(curve25519_dalek_bits = "32")]
pub(crate) use super::u32_constants::*;
// ------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------
#[cfg(test)]
mod test {
use super::*;
use crate::constants;
use crate::field::FieldElement;
#[test]
fn test_lizard_constants() {
let (_, sqrt_id) = FieldElement::sqrt_ratio_i(
&(&constants::SQRT_M1 * &constants::EDWARDS_D),
&FieldElement::ONE,
);
assert_eq!(sqrt_id, SQRT_ID);
assert_eq!(
&(&constants::EDWARDS_D + &FieldElement::ONE)
* &(&constants::EDWARDS_D - &FieldElement::ONE).invert(),
DP1_OVER_DM1
);
assert_eq!(
MDOUBLE_INVSQRT_A_MINUS_D,
-&(&constants::INVSQRT_A_MINUS_D + &constants::INVSQRT_A_MINUS_D)
);
assert_eq!(
MIDOUBLE_INVSQRT_A_MINUS_D,
&MDOUBLE_INVSQRT_A_MINUS_D * &constants::SQRT_M1
);
let (_, invsqrt_one_plus_d) = (&constants::EDWARDS_D + &FieldElement::ONE).invsqrt();
assert_eq!(-&invsqrt_one_plus_d, MINVSQRT_ONE_PLUS_D);
}
}

View file

@ -0,0 +1,403 @@
//! Defines additional methods on RistrettoPoint for Lizard
use digest::{
Digest, HashMarker,
array::Array,
consts::{U8, U16, U32},
};
use subtle::CtOption;
use crate::constants;
use crate::field::FieldElement;
use subtle::ConditionallySelectable;
use subtle::ConstantTimeEq;
use super::jacobi_quartic::JacobiPoint;
use super::lizard_constants;
use crate::ristretto::RistrettoPoint;
impl RistrettoPoint {
/// Encode 16 bytes of data to a RistrettoPoint, using the Lizard method. The secure hash
/// function `D` is used internally to produce a unique encoding for `data. Use SHA-256 if
/// otherwise unsure.
pub fn lizard_encode<D>(data: &[u8; 16]) -> RistrettoPoint
where
D: Digest<OutputSize = U32> + HashMarker,
{
let mut fe_bytes: [u8; 32] = Default::default();
let digest = D::digest(data);
fe_bytes[0..32].copy_from_slice(digest.as_slice());
fe_bytes[8..24].copy_from_slice(data);
// Clear the appropriate bits to be able to call map_to_curve_restricted
fe_bytes[31] &= 0b00111111;
fe_bytes[0] &= 0b11111110;
RistrettoPoint::map_to_curve_restricted(fe_bytes)
}
/// Decode 16 bytes of data from a RistrettoPoint, using the Lizard method. Returns `None` if
/// this point was not generated using Lizard.
pub fn lizard_decode<D>(&self) -> Option<[u8; 16]>
where
D: Digest<OutputSize = U32> + HashMarker,
{
let mut result: [u8; 16] = Default::default();
let fes = self.elligator_ristretto_flavor_inverse();
let mut n_found = 0;
for fe in fes {
let mut ok = fe.is_some();
let fe = fe.unwrap_or(FieldElement::ZERO);
let bytes = fe.to_bytes();
let mut expected_bytes: [u8; 32] = Default::default();
expected_bytes.copy_from_slice(&D::digest(&bytes[8..24]));
expected_bytes[8..24].copy_from_slice(&bytes[8..24]);
expected_bytes[0] &= 0b11111110;
expected_bytes[31] &= 0b00111111;
// If we found our inverse (there's at most 1), write the value to our output buffer
ok &= expected_bytes.ct_eq(&bytes);
for i in 0..16 {
// Copy bytes 8-24, since that's the payload
result[i] = u8::conditional_select(&result[i], &bytes[8 + i], ok);
}
n_found += ok.unwrap_u8();
}
// Per the README, the likelihood that n_found == 2 is something like 2^-122
if n_found == 1 { Some(result) } else { None }
}
/// Computes the at most 8 positive FieldElements f such that `self ==
/// RistrettoPoint::elligator_ristretto_flavor(f)`.
fn elligator_ristretto_flavor_inverse(&self) -> [CtOption<FieldElement>; 16] {
// Elligator2 computes a Point from a FieldElement in two steps: first
// it computes a (s,t) on the Jacobi quartic and then computes the
// corresponding even point on the Edwards curve.
//
// We invert in three steps. Any Ristretto point has four representatives
// as even Edwards points. For each of those even Edwards points,
// there are two points on the Jacobi quartic that map to it.
// Each of those eight points on the Jacobi quartic might have an
// Elligator2 preimage.
//
// Essentially we first loop over the four representatives of our point,
// then for each of them consider both points on the Jacobi quartic and
// check whether they have an inverse under Elligator2. We take the
// following shortcut though.
//
// We can compute two Jacobi quartic points for (x,y) and (-x,-y)
// at the same time. The four Jacobi quartic points are two of
// such pairs.
let jcs = self.to_jacobi_quartic_ristretto();
// Compute the positive solution to e⁻¹ on every point and its dual
let pos_invs = Array::<_, U8>::from_iter(
jcs.iter()
.flat_map(|jc| [jc.e_inv_positive(), jc.dual().e_inv_positive()]),
);
// Compute the other solutions to e⁻¹, ie the negatives of the above solutions
let neg_invs = pos_invs.iter().map(|mx| mx.map(|x| -&x));
// This cannot panic because jcs is guaranteed to be size 4, and the above iterator expands
// it to size 8
Array::<_, U16>::from_iter(pos_invs.into_iter().chain(neg_invs)).0
}
/// Find a point on the Jacobi quartic associated to each of the four
/// points Ristretto equivalent to p.
///
/// There is one exception: for (0,-1) there is no point on the quartic and
/// so we repeat one on the quartic equivalent to (0,1).
fn to_jacobi_quartic_ristretto(self) -> [JacobiPoint; 4] {
let x2 = self.0.X.square(); // X^2
let y2 = self.0.Y.square(); // Y^2
let y4 = y2.square(); // Y^4
let z2 = self.0.Z.square(); // Z^2
let z_min_y = &self.0.Z - &self.0.Y; // Z - Y
let z_pl_y = &self.0.Z + &self.0.Y; // Z + Y
let z2_min_y2 = &z2 - &y2; // Z^2 - Y^2
// gamma := 1/sqrt( Y^4 X^2 (Z^2 - Y^2) )
let (_, gamma) = (&(&y4 * &x2) * &z2_min_y2).invsqrt();
let den = &gamma * &y2;
let s_over_x = &den * &z_min_y;
let sp_over_xp = &den * &z_pl_y;
let s0 = &s_over_x * &self.0.X;
let s1 = &(-(&sp_over_xp)) * &self.0.X;
// t_0 := -2/sqrt(-d-1) * Z * sOverX
// t_1 := -2/sqrt(-d-1) * Z * spOverXp
let tmp = &lizard_constants::MDOUBLE_INVSQRT_A_MINUS_D * &self.0.Z;
let mut t0 = &tmp * &s_over_x;
let mut t1 = &tmp * &sp_over_xp;
// den := -1/sqrt(1+d) (Y^2 - Z^2) gamma
let den = &(&(-(&z2_min_y2)) * &lizard_constants::MINVSQRT_ONE_PLUS_D) * &gamma;
// Same as before but with the substitution (X, Y, Z) = (Y, X, i*Z)
let iz = &constants::SQRT_M1 * &self.0.Z; // iZ
let iz_min_x = &iz - &self.0.X; // iZ - X
let iz_pl_x = &iz + &self.0.X; // iZ + X
let s_over_y = &den * &iz_min_x;
let sp_over_yp = &den * &iz_pl_x;
let mut s2 = &s_over_y * &self.0.Y;
let mut s3 = &(-(&sp_over_yp)) * &self.0.Y;
// t_2 := -2/sqrt(-d-1) * i*Z * sOverY
// t_3 := -2/sqrt(-d-1) * i*Z * spOverYp
let tmp = &lizard_constants::MDOUBLE_INVSQRT_A_MINUS_D * &iz;
let mut t2 = &tmp * &s_over_y;
let mut t3 = &tmp * &sp_over_yp;
// Special case: X=0 or Y=0. Then return
//
// (0,1) (1,-2i/sqrt(-d-1) (-1,-2i/sqrt(-d-1))
//
// Note that if X=0 or Y=0, then s_i = t_i = 0.
let x_or_y_is_zero = self.0.X.is_zero() | self.0.Y.is_zero();
t0.conditional_assign(&FieldElement::ONE, x_or_y_is_zero);
t1.conditional_assign(&FieldElement::ONE, x_or_y_is_zero);
t2.conditional_assign(
&lizard_constants::MIDOUBLE_INVSQRT_A_MINUS_D,
x_or_y_is_zero,
);
t3.conditional_assign(
&lizard_constants::MIDOUBLE_INVSQRT_A_MINUS_D,
x_or_y_is_zero,
);
s2.conditional_assign(&FieldElement::ONE, x_or_y_is_zero);
s3.conditional_assign(&(-(&FieldElement::ONE)), x_or_y_is_zero);
[
JacobiPoint { S: s0, T: t0 },
JacobiPoint { S: s1, T: t1 },
JacobiPoint { S: s2, T: t2 },
JacobiPoint { S: s3, T: t3 },
]
}
/// Does the same as [`RistrettoPoint::map_to_curve`], but only operates on a restricted domain,
/// namely `bytes` with the bottom bit and the top two bits unset. It is guaranteed that
/// `map_to_curve_inverse(map_to_curve_restricted(bytes))` contains `bytes` in one of its first
/// 8 return values (i.e., the positive ones).
///
/// # Panics
/// Panics if the bottom bit (bottom bit of `bytes[0]`) or either of the top two bits (top two
/// bits of `bytes[31]`) are set.
pub fn map_to_curve_restricted(bytes: [u8; 32]) -> RistrettoPoint {
// Ensure it's a positive field element
assert_eq!(bytes[0] & 0b00000001, 0);
// Ensure it's less than below 2^254 (which is less than p)
assert_eq!(bytes[31] & 0b11000000, 0);
RistrettoPoint::map_to_curve(bytes)
}
/// Computes the possible bytestrings that could have produced this point via
/// [`Self::map_to_curve`].
///
/// The first 8 return values are positive field elements (i.e., have the LSB (`bytes[0] & 1`)
/// unset), if defined. The last 8 return values are negative field elements (i.e., have the LSB
/// set), if defined.
pub fn map_to_curve_inverse(&self) -> [CtOption<[u8; 32]>; 16] {
// Compute the inverses
let fes = self.elligator_ristretto_flavor_inverse();
// Serialize the field elements
let it = fes.map(|fe| fe.map(|f| f.to_bytes()));
Array::<_, U16>::from_iter(it).0
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{edwards::EdwardsPoint, ristretto::CompressedRistretto};
use rand_core::RngCore;
use sha2::Sha256;
/// Return the coset self + E\[4\]
fn xcoset4(pt: &RistrettoPoint) -> [EdwardsPoint; 4] {
[
pt.0,
pt.0 + constants::EIGHT_TORSION[2],
pt.0 + constants::EIGHT_TORSION[4],
pt.0 + constants::EIGHT_TORSION[6],
]
}
/// Checks
/// `lizard_decode(lizard_encode(data)) == lizard_decode(expected_pt_bytes) == data`
fn test_lizard_encode_helper(data: &[u8], expected_pt_bytes: &[u8]) {
assert_eq!(data.len(), 16);
assert_eq!(expected_pt_bytes.len(), 32);
let p = RistrettoPoint::lizard_encode::<Sha256>(data.try_into().unwrap());
let pt_bytes = p.compress().to_bytes();
assert!(pt_bytes == expected_pt_bytes);
let p = CompressedRistretto::from_slice(&pt_bytes)
.unwrap()
.decompress()
.unwrap();
let data_out = p.lizard_decode::<Sha256>().unwrap();
assert!(&data_out == data);
}
#[test]
fn lizard_encode() {
// Test vectors are of the form (x, y) where y is the compressed encoding of the Ristretto
// point given by lizard_encode(x).
// These values come from the testLizard() function in vendor/ristretto.sage
let test_vectors = [
(
"00000000000000000000000000000000",
"f0b7e34484f74cf00f15024b738539738646bbbe1e9bc7509a676815227e774f",
),
(
"01010101010101010101010101010101",
"cc92e81f585afc5caac88660d8d17e9025a44489a363042123f6af0702156e65",
),
(
"000102030405060708090a0b0c0d0e0f",
"c830573f8a8e7778671f76cdc796dc0a235cf177f197d9fcba06e84e96247444",
),
(
"dddddddddddddddddddddddddddddddd",
"ccb60554c081841037f821fa827b6a5bc2531f80e2647f1a858611f4ccfe3056",
),
];
for tv in test_vectors {
test_lizard_encode_helper(&hex::decode(tv.0).unwrap(), &hex::decode(tv.1).unwrap());
}
}
// Tests that lizard_decode of a random point is None
#[test]
fn lizard_invalid() {
let mut rng = rand::rng();
for _ in 0..100 {
let pt = RistrettoPoint::random(&mut rng);
assert!(
pt.lizard_decode::<Sha256>().is_none(),
"random point {:02x?} is a valid Lizard encoding",
pt.compress().to_bytes()
)
}
}
// Test that
// elligator_ristretto_flavor ○ elligator_ristretto_flavor_inverse ○ elligator_ristretto_flavor
// is the identity
#[test]
fn elligator_inv() {
let mut rng = rand::rng();
for i in 0..100 {
let mut fe_bytes = [0u8; 32];
if i == 0 {
// Test for first corner-case: fe = 0
fe_bytes = [0u8; 32];
} else if i == 1 {
// Test for second corner-case: fe = +sqrt(i*d)
fe_bytes = [
168, 27, 92, 74, 203, 42, 48, 117, 170, 109, 234, 14, 45, 169, 188, 205, 21,
110, 235, 115, 153, 84, 52, 117, 151, 235, 123, 244, 88, 85, 179, 5,
];
} else {
// For the rest, just generate a random field element to test.
rng.fill_bytes(&mut fe_bytes);
}
// Make fe positive (even) and less than the modulus
fe_bytes[0] &= 254;
fe_bytes[31] &= 127;
let fe = FieldElement::from_bytes(&fe_bytes);
let pt = RistrettoPoint::elligator_ristretto_flavor(&fe);
for pt2 in xcoset4(&pt) {
let fes = RistrettoPoint(pt2).elligator_ristretto_flavor_inverse();
let mut found = false;
for fe_j in fes {
if fe_j.is_some().into() {
let fe_j = fe_j.unwrap();
assert_eq!(RistrettoPoint::elligator_ristretto_flavor(&fe_j), pt);
if fe_j == fe {
found = true;
}
}
}
assert!(found);
}
}
}
// Tests that map_to_curve ○ map_to_curve_inverse is the identity
#[test]
fn map_to_curve_inverse() {
let mut rng = rand::rng();
for _ in 0..100 {
let mut input = [0u8; 32];
rng.fill_bytes(&mut input);
// Map to Ristretto and invert it
let pt = RistrettoPoint::map_to_curve(input);
let inverses = pt.map_to_curve_inverse();
// Assert at least one inverse exists, and all the inverses map to pt
assert!(inverses.iter().any(|i| bool::from(i.is_some())));
for inv in inverses.into_iter().filter_map(CtOption::into_option) {
assert_eq!(pt, RistrettoPoint::map_to_curve(inv));
}
}
}
// Tests that map_to_curve_inverse ○ map_to_curve_restricted is the identity and has a non-None
// return value in the first 8 elements
#[test]
fn map_pos_felem_to_curve_inverse() {
let mut rng = rand::rng();
for _ in 0..100 {
let mut input = [0u8; 32];
rng.fill_bytes(&mut input);
// Clear bits so we can call map_to_curve_restricted
input[31] &= 0b00111111;
input[0] &= 0b11111110;
let pt = RistrettoPoint::map_to_curve_restricted(input);
let inverses = pt.map_to_curve_inverse();
// Check that one of the valid inverses matches the input
let mut found = false;
for (i, inv) in inverses.into_iter().enumerate() {
if inv.is_some().into() && inv.unwrap() == input {
// map_to_curve_inverse returns all the positive solutions in the first 8
// values, and all the negative solution in the second 8 values
if i >= 8 {
panic!("input is in the latter 8 inverses ({input:02x?})");
}
// Per the README, the probability of finding two inverses is ~2^-122
if found == true {
panic!("found two inverses ({input:02x?})");
}
found = true;
}
}
if !found {
panic!("did not find inverse for input {:02x?}", input);
}
}
}
}

View file

@ -0,0 +1,13 @@
//! The Lizard method for encoding/decoding 16 bytes into Ristretto points.
#![allow(non_snake_case)]
#[cfg(curve25519_dalek_bits = "32")]
mod u32_constants;
#[cfg(curve25519_dalek_bits = "64")]
mod u64_constants;
mod jacobi_quartic;
mod lizard_constants;
pub mod lizard_ristretto;

View file

@ -0,0 +1,46 @@
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(curve25519_dalek_backend = "fiat")] {
pub use crate::backend::serial::fiat_u32::field::FieldElement2625;
const fn field_element(element: [u32; 10]) -> FieldElement2625 {
FieldElement2625(fiat_crypto::curve25519_32::fiat_25519_tight_field_element(element))
}
} else {
pub use crate::backend::serial::u32::field::FieldElement2625;
const fn field_element(element: [u32; 10]) -> FieldElement2625 {
FieldElement2625(element)
}
}
}
/// `= sqrt(i*d)`, where `i = +sqrt(-1)` and `d` is the Edwards curve parameter.
pub const SQRT_ID: FieldElement2625 = field_element([
39590824, 701138, 28659366, 23623507, 53932708, 32206357, 36326585, 24309414, 26167230, 1494357,
]);
/// `= (d+1)/(d-1)`, where `d` is the Edwards curve parameter.
pub const DP1_OVER_DM1: FieldElement2625 = field_element([
58833708, 32184294, 62457071, 26110240, 19032991, 27203620, 7122892, 18068959, 51019405,
3776288,
]);
/// `= -2/sqrt(a-d)`, where `a = -1 (mod p)`, `d` are the Edwards curve parameters.
pub const MDOUBLE_INVSQRT_A_MINUS_D: FieldElement2625 = field_element([
54885894, 25242303, 55597453, 9067496, 51808079, 33312638, 25456129, 14121551, 54921728,
3972023,
]);
/// `= -2i/sqrt(a-d)`, where `a = -1 (mod p)`, `d` are the Edwards curve parameters
/// and `i = +sqrt(-1)`.
pub const MIDOUBLE_INVSQRT_A_MINUS_D: FieldElement2625 = field_element([
58178520, 23970840, 26444491, 29801899, 41064376, 743696, 2900628, 27920316, 41968995, 5270573,
]);
/// `= -1/sqrt(1+d)`, where `d` is the Edwards curve parameters.
pub const MINVSQRT_ONE_PLUS_D: FieldElement2625 = field_element([
38019585, 4791795, 20332186, 18653482, 46576675, 33182583, 65658549, 2817057, 12569934,
30919145,
]);

View file

@ -0,0 +1,63 @@
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(curve25519_dalek_backend = "fiat")] {
pub use crate::backend::serial::fiat_u64::field::FieldElement51;
const fn field_element(element: [u64; 5]) -> FieldElement51 {
FieldElement51(fiat_crypto::curve25519_64::fiat_25519_tight_field_element(element))
}
} else {
pub use crate::backend::serial::u64::field::FieldElement51;
const fn field_element(element: [u64; 5]) -> FieldElement51 {
FieldElement51(element)
}
}
}
/// `= sqrt(i*d)`, where `i = +sqrt(-1)` and `d` is the Edwards curve parameter.
pub const SQRT_ID: FieldElement51 = field_element([
2298852427963285,
3837146560810661,
4413131899466403,
3883177008057528,
2352084440532925,
]);
/// `= (d+1)/(d-1)`, where `d` is the Edwards curve parameter.
pub const DP1_OVER_DM1: FieldElement51 = field_element([
2159851467815724,
1752228607624431,
1825604053920671,
1212587319275468,
253422448836237,
]);
/// `= -2/sqrt(a-d)`, where `a = -1 (mod p)`, `d` are the Edwards curve parameters.
pub const MDOUBLE_INVSQRT_A_MINUS_D: FieldElement51 = field_element([
1693982333959686,
608509411481997,
2235573344831311,
947681270984193,
266558006233600,
]);
/// `= -2i/sqrt(a-d)`, where `a = -1 (mod p)`, `d` are the Edwards curve parameters
/// and `i = +sqrt(-1)`.
pub const MIDOUBLE_INVSQRT_A_MINUS_D: FieldElement51 = field_element([
1608655899704280,
1999971613377227,
49908634785720,
1873700692181652,
353702208628067,
]);
/// `= -1/sqrt(1+d)`, where `d` is the Edwards curve parameters.
pub const MINVSQRT_ONE_PLUS_D: FieldElement51 = field_element([
321571956990465,
1251814006996634,
2226845496292387,
189049560751797,
2074948709371214,
]);

View file

@ -0,0 +1,389 @@
//! Contains methods implementing Elligator2 maps from [RFC 9496](https://www.rfc-editor.org/rfc/rfc9496.html)
use crate::{constants, field::FieldElement, ristretto::RistrettoPoint};
use subtle::{ConditionallyNegatable, ConditionallySelectable};
impl RistrettoPoint {
/// Computes the Ristretto Elligator map for the given field element. This is the second half of
/// the [`MAP`](https://www.rfc-editor.org/rfc/rfc9496.html#section-4.3.4-4) function defined in
/// the Ristretto spec.
///
/// # Note
///
/// This method is not public because it's just used for hashing
/// to a point -- proper elligator support is deferred for now.
pub(crate) fn elligator_ristretto_flavor(r_0: &FieldElement) -> RistrettoPoint {
let i = &constants::SQRT_M1;
let d = &constants::EDWARDS_D;
let one_minus_d_sq = &constants::ONE_MINUS_EDWARDS_D_SQUARED;
let d_minus_one_sq = &constants::EDWARDS_D_MINUS_ONE_SQUARED;
let mut c = constants::MINUS_ONE;
let one = FieldElement::ONE;
let r = i * &r_0.square();
let N_s = &(&r + &one) * one_minus_d_sq;
let D = &(&c - &(d * &r)) * &(&r + d);
let (Ns_D_is_sq, mut s) = FieldElement::sqrt_ratio_i(&N_s, &D);
let mut s_prime = &s * r_0;
let s_prime_is_pos = !s_prime.is_negative();
s_prime.conditional_negate(s_prime_is_pos);
s.conditional_assign(&s_prime, !Ns_D_is_sq);
c.conditional_assign(&r, !Ns_D_is_sq);
let N_t = &(&(&c * &(&r - &one)) * d_minus_one_sq) - &D;
let s_sq = s.square();
use crate::backend::serial::curve_models::CompletedPoint;
// The conversion from W_i is exactly the conversion from P1xP1.
RistrettoPoint(
CompletedPoint {
X: &(&s + &s) * &D,
Z: &N_t * &constants::SQRT_AD_MINUS_ONE,
Y: &FieldElement::ONE - &s_sq,
T: &FieldElement::ONE + &s_sq,
}
.as_extended(),
)
}
/// Interprets the given bytestring as a field element and computes the Ristretto Elligator map.
/// This is the [MAP](https://www.rfc-editor.org/rfc/rfc9496.html#section-4.3.4-4) function in
/// RFC 9496.
///
/// # Warning
///
/// This function does not produce cryptographically random-looking Ristretto points. Use
/// [`Self::from_uniform_bytes`] or [`Self::hash_from_bytes`] for that. DO NOT USE THIS FUNCTION
/// unless you really know what you're doing.
pub fn map_to_curve(bytes: [u8; 32]) -> RistrettoPoint {
// MAP must clear the top bit. This is done in `from_bytes` for every field backend, so we
// don't have to do it ourselves here
let fe = FieldElement::from_bytes(&bytes);
RistrettoPoint::elligator_ristretto_flavor(&fe)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::ristretto::CompressedRistretto;
#[test]
fn elligator_vs_ristretto_sage() {
// Test vectors extracted from ristretto.sage.
//
// Notice that all of the byte sequences have bit 255 set to 0; this is because
// ristretto.sage does not mask the high bit of a field element. When the high bit is set,
// the ristretto.sage elligator implementation gives different results, since it takes a
// different field element as input.
let bytes: [[u8; 32]; 16] = [
[
184, 249, 135, 49, 253, 123, 89, 113, 67, 160, 6, 239, 7, 105, 211, 41, 192, 249,
185, 57, 9, 102, 70, 198, 15, 127, 7, 26, 160, 102, 134, 71,
],
[
229, 14, 241, 227, 75, 9, 118, 60, 128, 153, 226, 21, 183, 217, 91, 136, 98, 0,
231, 156, 124, 77, 82, 139, 142, 134, 164, 169, 169, 62, 250, 52,
],
[
115, 109, 36, 220, 180, 223, 99, 6, 204, 169, 19, 29, 169, 68, 84, 23, 21, 109,
189, 149, 127, 205, 91, 102, 172, 35, 112, 35, 134, 69, 186, 34,
],
[
16, 49, 96, 107, 171, 199, 164, 9, 129, 16, 64, 62, 241, 63, 132, 173, 209, 160,
112, 215, 105, 50, 157, 81, 253, 105, 1, 154, 229, 25, 120, 83,
],
[
156, 131, 161, 162, 236, 251, 5, 187, 167, 171, 17, 178, 148, 210, 90, 207, 86, 21,
79, 161, 167, 215, 234, 1, 136, 242, 182, 248, 38, 85, 79, 86,
],
[
251, 177, 124, 54, 18, 101, 75, 235, 245, 186, 19, 46, 133, 157, 229, 64, 10, 136,
181, 185, 78, 144, 254, 167, 137, 49, 107, 10, 61, 10, 21, 25,
],
[
232, 193, 20, 68, 240, 77, 186, 77, 183, 40, 44, 86, 150, 31, 198, 212, 76, 81, 3,
217, 197, 8, 126, 128, 126, 152, 164, 208, 153, 44, 189, 77,
],
[
173, 229, 149, 177, 37, 230, 30, 69, 61, 56, 172, 190, 219, 115, 167, 194, 71, 134,
59, 75, 28, 244, 118, 26, 162, 97, 64, 16, 15, 189, 30, 64,
],
[
106, 71, 61, 107, 250, 117, 42, 151, 91, 202, 212, 100, 52, 188, 190, 21, 125, 218,
31, 18, 253, 241, 160, 133, 57, 242, 3, 164, 189, 68, 111, 75,
],
[
112, 204, 182, 90, 220, 198, 120, 73, 173, 107, 193, 17, 227, 40, 162, 36, 150,
141, 235, 55, 172, 183, 12, 39, 194, 136, 43, 153, 244, 118, 91, 89,
],
[
111, 24, 203, 123, 254, 189, 11, 162, 51, 196, 163, 136, 204, 143, 10, 222, 33,
112, 81, 205, 34, 35, 8, 66, 90, 6, 164, 58, 170, 177, 34, 25,
],
[
225, 183, 30, 52, 236, 82, 6, 183, 109, 25, 227, 181, 25, 82, 41, 193, 80, 77, 161,
80, 242, 203, 79, 204, 136, 245, 131, 110, 237, 106, 3, 58,
],
[
207, 246, 38, 56, 30, 86, 176, 90, 27, 200, 61, 42, 221, 27, 56, 210, 79, 178, 189,
120, 68, 193, 120, 167, 77, 185, 53, 197, 124, 128, 191, 126,
],
[
1, 136, 215, 80, 240, 46, 63, 147, 16, 244, 230, 207, 82, 189, 74, 50, 106, 169,
138, 86, 30, 131, 214, 202, 166, 125, 251, 228, 98, 24, 36, 21,
],
[
210, 207, 228, 56, 155, 116, 207, 54, 84, 195, 251, 215, 249, 199, 116, 75, 109,
239, 196, 251, 194, 246, 252, 228, 70, 146, 156, 35, 25, 39, 241, 4,
],
[
34, 116, 123, 9, 8, 40, 93, 189, 9, 103, 57, 103, 66, 227, 3, 2, 157, 107, 134,
219, 202, 74, 230, 154, 78, 107, 219, 195, 214, 14, 84, 80,
],
];
let encoded_images: [CompressedRistretto; 16] = [
CompressedRistretto([
176, 157, 237, 97, 66, 29, 140, 166, 168, 94, 26, 157, 212, 216, 229, 160, 195,
246, 232, 239, 169, 112, 63, 193, 64, 32, 152, 69, 11, 190, 246, 86,
]),
CompressedRistretto([
234, 141, 77, 203, 181, 225, 250, 74, 171, 62, 15, 118, 78, 212, 150, 19, 131, 14,
188, 238, 194, 244, 141, 138, 166, 162, 83, 122, 228, 201, 19, 26,
]),
CompressedRistretto([
232, 231, 51, 92, 5, 168, 80, 36, 173, 179, 104, 68, 186, 149, 68, 40, 140, 170,
27, 103, 99, 140, 21, 242, 43, 62, 250, 134, 208, 255, 61, 89,
]),
CompressedRistretto([
208, 120, 140, 129, 177, 179, 237, 159, 252, 160, 28, 13, 206, 5, 211, 241, 192,
218, 1, 97, 130, 241, 20, 169, 119, 46, 246, 29, 79, 80, 77, 84,
]),
CompressedRistretto([
202, 11, 236, 145, 58, 12, 181, 157, 209, 6, 213, 88, 75, 147, 11, 119, 191, 139,
47, 142, 33, 36, 153, 193, 223, 183, 178, 8, 205, 120, 248, 110,
]),
CompressedRistretto([
26, 66, 231, 67, 203, 175, 116, 130, 32, 136, 62, 253, 215, 46, 5, 214, 166, 248,
108, 237, 216, 71, 244, 173, 72, 133, 82, 6, 143, 240, 104, 41,
]),
CompressedRistretto([
40, 157, 102, 96, 201, 223, 200, 197, 150, 181, 106, 83, 103, 126, 143, 33, 145,
230, 78, 6, 171, 146, 210, 143, 112, 5, 245, 23, 183, 138, 18, 120,
]),
CompressedRistretto([
220, 37, 27, 203, 239, 196, 176, 131, 37, 66, 188, 243, 185, 250, 113, 23, 167,
211, 154, 243, 168, 215, 54, 171, 159, 36, 195, 81, 13, 150, 43, 43,
]),
CompressedRistretto([
232, 121, 176, 222, 183, 196, 159, 90, 238, 193, 105, 52, 101, 167, 244, 170, 121,
114, 196, 6, 67, 152, 80, 185, 221, 7, 83, 105, 176, 208, 224, 121,
]),
CompressedRistretto([
226, 181, 183, 52, 241, 163, 61, 179, 221, 207, 220, 73, 245, 242, 25, 236, 67, 84,
179, 222, 167, 62, 167, 182, 32, 9, 92, 30, 165, 127, 204, 68,
]),
CompressedRistretto([
226, 119, 16, 242, 200, 139, 240, 87, 11, 222, 92, 146, 156, 243, 46, 119, 65, 59,
1, 248, 92, 183, 50, 175, 87, 40, 206, 53, 208, 220, 148, 13,
]),
CompressedRistretto([
70, 240, 79, 112, 54, 157, 228, 146, 74, 122, 216, 88, 232, 62, 158, 13, 14, 146,
115, 117, 176, 222, 90, 225, 244, 23, 94, 190, 150, 7, 136, 96,
]),
CompressedRistretto([
22, 71, 241, 103, 45, 193, 195, 144, 183, 101, 154, 50, 39, 68, 49, 110, 51, 44,
62, 0, 229, 113, 72, 81, 168, 29, 73, 106, 102, 40, 132, 24,
]),
CompressedRistretto([
196, 133, 107, 11, 130, 105, 74, 33, 204, 171, 133, 221, 174, 193, 241, 36, 38,
179, 196, 107, 219, 185, 181, 253, 228, 47, 155, 42, 231, 73, 41, 78,
]),
CompressedRistretto([
58, 255, 225, 197, 115, 208, 160, 143, 39, 197, 82, 69, 143, 235, 92, 170, 74, 40,
57, 11, 171, 227, 26, 185, 217, 207, 90, 185, 197, 190, 35, 60,
]),
CompressedRistretto([
88, 43, 92, 118, 223, 136, 105, 145, 238, 186, 115, 8, 214, 112, 153, 253, 38, 108,
205, 230, 157, 130, 11, 66, 101, 85, 253, 110, 110, 14, 148, 112,
]),
];
for i in 0..16 {
let r_0 = FieldElement::from_bytes(&bytes[i]);
let Q = RistrettoPoint::elligator_ristretto_flavor(&r_0);
assert_eq!(Q.compress(), encoded_images[i]);
}
}
// Known answer tests for the one-way mapping function in the Ristretto RFC
#[test]
fn one_way_map() {
// These inputs are from
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-04#appendix-A.3
let test_vectors: &[([u8; 64], CompressedRistretto)] = &[
(
[
0x5d, 0x1b, 0xe0, 0x9e, 0x3d, 0x0c, 0x82, 0xfc, 0x53, 0x81, 0x12, 0x49, 0x0e,
0x35, 0x70, 0x19, 0x79, 0xd9, 0x9e, 0x06, 0xca, 0x3e, 0x2b, 0x5b, 0x54, 0xbf,
0xfe, 0x8b, 0x4d, 0xc7, 0x72, 0xc1, 0x4d, 0x98, 0xb6, 0x96, 0xa1, 0xbb, 0xfb,
0x5c, 0xa3, 0x2c, 0x43, 0x6c, 0xc6, 0x1c, 0x16, 0x56, 0x37, 0x90, 0x30, 0x6c,
0x79, 0xea, 0xca, 0x77, 0x05, 0x66, 0x8b, 0x47, 0xdf, 0xfe, 0x5b, 0xb6,
],
CompressedRistretto([
0x30, 0x66, 0xf8, 0x2a, 0x1a, 0x74, 0x7d, 0x45, 0x12, 0x0d, 0x17, 0x40, 0xf1,
0x43, 0x58, 0x53, 0x1a, 0x8f, 0x04, 0xbb, 0xff, 0xe6, 0xa8, 0x19, 0xf8, 0x6d,
0xfe, 0x50, 0xf4, 0x4a, 0x0a, 0x46,
]),
),
(
[
0xf1, 0x16, 0xb3, 0x4b, 0x8f, 0x17, 0xce, 0xb5, 0x6e, 0x87, 0x32, 0xa6, 0x0d,
0x91, 0x3d, 0xd1, 0x0c, 0xce, 0x47, 0xa6, 0xd5, 0x3b, 0xee, 0x92, 0x04, 0xbe,
0x8b, 0x44, 0xf6, 0x67, 0x8b, 0x27, 0x01, 0x02, 0xa5, 0x69, 0x02, 0xe2, 0x48,
0x8c, 0x46, 0x12, 0x0e, 0x92, 0x76, 0xcf, 0xe5, 0x46, 0x38, 0x28, 0x6b, 0x9e,
0x4b, 0x3c, 0xdb, 0x47, 0x0b, 0x54, 0x2d, 0x46, 0xc2, 0x06, 0x8d, 0x38,
],
CompressedRistretto([
0xf2, 0x6e, 0x5b, 0x6f, 0x7d, 0x36, 0x2d, 0x2d, 0x2a, 0x94, 0xc5, 0xd0, 0xe7,
0x60, 0x2c, 0xb4, 0x77, 0x3c, 0x95, 0xa2, 0xe5, 0xc3, 0x1a, 0x64, 0xf1, 0x33,
0x18, 0x9f, 0xa7, 0x6e, 0xd6, 0x1b,
]),
),
(
[
0x84, 0x22, 0xe1, 0xbb, 0xda, 0xab, 0x52, 0x93, 0x8b, 0x81, 0xfd, 0x60, 0x2e,
0xff, 0xb6, 0xf8, 0x91, 0x10, 0xe1, 0xe5, 0x72, 0x08, 0xad, 0x12, 0xd9, 0xad,
0x76, 0x7e, 0x2e, 0x25, 0x51, 0x0c, 0x27, 0x14, 0x07, 0x75, 0xf9, 0x33, 0x70,
0x88, 0xb9, 0x82, 0xd8, 0x3d, 0x7f, 0xcf, 0x0b, 0x2f, 0xa1, 0xed, 0xff, 0xe5,
0x19, 0x52, 0xcb, 0xe7, 0x36, 0x5e, 0x95, 0xc8, 0x6e, 0xaf, 0x32, 0x5c,
],
CompressedRistretto([
0x00, 0x6c, 0xcd, 0x2a, 0x9e, 0x68, 0x67, 0xe6, 0xa2, 0xc5, 0xce, 0xa8, 0x3d,
0x33, 0x02, 0xcc, 0x9d, 0xe1, 0x28, 0xdd, 0x2a, 0x9a, 0x57, 0xdd, 0x8e, 0xe7,
0xb9, 0xd7, 0xff, 0xe0, 0x28, 0x26,
]),
),
(
[
0xac, 0x22, 0x41, 0x51, 0x29, 0xb6, 0x14, 0x27, 0xbf, 0x46, 0x4e, 0x17, 0xba,
0xee, 0x8d, 0xb6, 0x59, 0x40, 0xc2, 0x33, 0xb9, 0x8a, 0xfc, 0xe8, 0xd1, 0x7c,
0x57, 0xbe, 0xeb, 0x78, 0x76, 0xc2, 0x15, 0x0d, 0x15, 0xaf, 0x1c, 0xb1, 0xfb,
0x82, 0x4b, 0xbd, 0x14, 0x95, 0x5f, 0x2b, 0x57, 0xd0, 0x8d, 0x38, 0x8a, 0xab,
0x43, 0x1a, 0x39, 0x1c, 0xfc, 0x33, 0xd5, 0xba, 0xfb, 0x5d, 0xbb, 0xaf,
],
CompressedRistretto([
0xf8, 0xf0, 0xc8, 0x7c, 0xf2, 0x37, 0x95, 0x3c, 0x58, 0x90, 0xae, 0xc3, 0x99,
0x81, 0x69, 0x00, 0x5d, 0xae, 0x3e, 0xca, 0x1f, 0xbb, 0x04, 0x54, 0x8c, 0x63,
0x59, 0x53, 0xc8, 0x17, 0xf9, 0x2a,
]),
),
(
[
0x16, 0x5d, 0x69, 0x7a, 0x1e, 0xf3, 0xd5, 0xcf, 0x3c, 0x38, 0x56, 0x5b, 0xee,
0xfc, 0xf8, 0x8c, 0x0f, 0x28, 0x2b, 0x8e, 0x7d, 0xbd, 0x28, 0x54, 0x4c, 0x48,
0x34, 0x32, 0xf1, 0xce, 0xc7, 0x67, 0x5d, 0xeb, 0xea, 0x8e, 0xbb, 0x4e, 0x5f,
0xe7, 0xd6, 0xf6, 0xe5, 0xdb, 0x15, 0xf1, 0x55, 0x87, 0xac, 0x4d, 0x4d, 0x4a,
0x1d, 0xe7, 0x19, 0x1e, 0x0c, 0x1c, 0xa6, 0x66, 0x4a, 0xbc, 0xc4, 0x13,
],
CompressedRistretto([
0xae, 0x81, 0xe7, 0xde, 0xdf, 0x20, 0xa4, 0x97, 0xe1, 0x0c, 0x30, 0x4a, 0x76,
0x5c, 0x17, 0x67, 0xa4, 0x2d, 0x6e, 0x06, 0x02, 0x97, 0x58, 0xd2, 0xd7, 0xe8,
0xef, 0x7c, 0xc4, 0xc4, 0x11, 0x79,
]),
),
(
[
0xa8, 0x36, 0xe6, 0xc9, 0xa9, 0xca, 0x9f, 0x1e, 0x8d, 0x48, 0x62, 0x73, 0xad,
0x56, 0xa7, 0x8c, 0x70, 0xcf, 0x18, 0xf0, 0xce, 0x10, 0xab, 0xb1, 0xc7, 0x17,
0x2d, 0xdd, 0x60, 0x5d, 0x7f, 0xd2, 0x97, 0x98, 0x54, 0xf4, 0x7a, 0xe1, 0xcc,
0xf2, 0x04, 0xa3, 0x31, 0x02, 0x09, 0x5b, 0x42, 0x00, 0xe5, 0xbe, 0xfc, 0x04,
0x65, 0xac, 0xcc, 0x26, 0x31, 0x75, 0x48, 0x5f, 0x0e, 0x17, 0xea, 0x5c,
],
CompressedRistretto([
0xe2, 0x70, 0x56, 0x52, 0xff, 0x9f, 0x5e, 0x44, 0xd3, 0xe8, 0x41, 0xbf, 0x1c,
0x25, 0x1c, 0xf7, 0xdd, 0xdb, 0x77, 0xd1, 0x40, 0x87, 0x0d, 0x1a, 0xb2, 0xed,
0x64, 0xf1, 0xa9, 0xce, 0x86, 0x28,
]),
),
(
[
0x2c, 0xdc, 0x11, 0xea, 0xeb, 0x95, 0xda, 0xf0, 0x11, 0x89, 0x41, 0x7c, 0xdd,
0xdb, 0xf9, 0x59, 0x52, 0x99, 0x3a, 0xa9, 0xcb, 0x9c, 0x64, 0x0e, 0xb5, 0x05,
0x8d, 0x09, 0x70, 0x2c, 0x74, 0x62, 0x2c, 0x99, 0x65, 0xa6, 0x97, 0xa3, 0xb3,
0x45, 0xec, 0x24, 0xee, 0x56, 0x33, 0x5b, 0x55, 0x6e, 0x67, 0x7b, 0x30, 0xe6,
0xf9, 0x0a, 0xc7, 0x7d, 0x78, 0x10, 0x64, 0xf8, 0x66, 0xa3, 0xc9, 0x82,
],
CompressedRistretto([
0x80, 0xbd, 0x07, 0x26, 0x25, 0x11, 0xcd, 0xde, 0x48, 0x63, 0xf8, 0xa7, 0x43,
0x4c, 0xef, 0x69, 0x67, 0x50, 0x68, 0x1c, 0xb9, 0x51, 0x0e, 0xea, 0x55, 0x70,
0x88, 0xf7, 0x6d, 0x9e, 0x50, 0x65,
]),
),
(
[
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
CompressedRistretto([
0x30, 0x42, 0x82, 0x79, 0x10, 0x23, 0xb7, 0x31, 0x28, 0xd2, 0x77, 0xbd, 0xcb,
0x5c, 0x77, 0x46, 0xef, 0x2e, 0xac, 0x08, 0xdd, 0xe9, 0xf2, 0x98, 0x33, 0x79,
0xcb, 0x8e, 0x5e, 0xf0, 0x51, 0x7f,
]),
),
(
[
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
],
CompressedRistretto([
0x30, 0x42, 0x82, 0x79, 0x10, 0x23, 0xb7, 0x31, 0x28, 0xd2, 0x77, 0xbd, 0xcb,
0x5c, 0x77, 0x46, 0xef, 0x2e, 0xac, 0x08, 0xdd, 0xe9, 0xf2, 0x98, 0x33, 0x79,
0xcb, 0x8e, 0x5e, 0xf0, 0x51, 0x7f,
]),
),
(
[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
],
CompressedRistretto([
0x30, 0x42, 0x82, 0x79, 0x10, 0x23, 0xb7, 0x31, 0x28, 0xd2, 0x77, 0xbd, 0xcb,
0x5c, 0x77, 0x46, 0xef, 0x2e, 0xac, 0x08, 0xdd, 0xe9, 0xf2, 0x98, 0x33, 0x79,
0xcb, 0x8e, 0x5e, 0xf0, 0x51, 0x7f,
]),
),
(
[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
],
CompressedRistretto([
0x30, 0x42, 0x82, 0x79, 0x10, 0x23, 0xb7, 0x31, 0x28, 0xd2, 0x77, 0xbd, 0xcb,
0x5c, 0x77, 0x46, 0xef, 0x2e, 0xac, 0x08, 0xdd, 0xe9, 0xf2, 0x98, 0x33, 0x79,
0xcb, 0x8e, 0x5e, 0xf0, 0x51, 0x7f,
]),
),
];
// Check that onewaymap(input) == output for all the above vectors
for (input, output) in test_vectors {
let Q = RistrettoPoint::from_uniform_bytes(input);
assert_eq!(&Q.compress(), output);
}
}
}

View file

@ -119,8 +119,6 @@
//! `RistrettoPoint::hash_from_bytes()`, which perform hashing to the
//! group.
//!
//! The Elligator map itself is not currently exposed.
//!
//! ## Implementation
//!
//! The Decaf suggestion is to use a quotient group, such as \\(\mathcal
@ -158,6 +156,8 @@
//! [ristretto_main]:
//! https://ristretto.group/
mod elligator;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
@ -656,52 +656,6 @@ impl RistrettoPoint {
]
}
/// Computes the Ristretto Elligator map. This is the
/// [`MAP`](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-04#section-4.3.4)
/// function defined in the Ristretto spec.
///
/// # Note
///
/// This method is not public because it's just used for hashing
/// to a point -- proper elligator support is deferred for now.
pub(crate) fn elligator_ristretto_flavor(r_0: &FieldElement) -> RistrettoPoint {
let i = &constants::SQRT_M1;
let d = &constants::EDWARDS_D;
let one_minus_d_sq = &constants::ONE_MINUS_EDWARDS_D_SQUARED;
let d_minus_one_sq = &constants::EDWARDS_D_MINUS_ONE_SQUARED;
let mut c = constants::MINUS_ONE;
let one = FieldElement::ONE;
let r = i * &r_0.square();
let N_s = &(&r + &one) * one_minus_d_sq;
let D = &(&c - &(d * &r)) * &(&r + d);
let (Ns_D_is_sq, mut s) = FieldElement::sqrt_ratio_i(&N_s, &D);
let mut s_prime = &s * r_0;
let s_prime_is_pos = !s_prime.is_negative();
s_prime.conditional_negate(s_prime_is_pos);
s.conditional_assign(&s_prime, !Ns_D_is_sq);
c.conditional_assign(&r, !Ns_D_is_sq);
let N_t = &(&(&c * &(&r - &one)) * d_minus_one_sq) - &D;
let s_sq = s.square();
use crate::backend::serial::curve_models::CompletedPoint;
// The conversion from W_i is exactly the conversion from P1xP1.
RistrettoPoint(
CompletedPoint {
X: &(&s + &s) * &D,
Z: &N_t * &constants::SQRT_AD_MINUS_ONE,
Y: &FieldElement::ONE - &s_sq,
T: &FieldElement::ONE + &s_sq,
}
.as_extended(),
)
}
#[cfg(any(test, feature = "rand_core"))]
/// Return a `RistrettoPoint` chosen uniformly at random using a user-provided RNG.
///
@ -1525,321 +1479,6 @@ mod test {
}
}
#[test]
fn elligator_vs_ristretto_sage() {
// Test vectors extracted from ristretto.sage.
//
// Notice that all of the byte sequences have bit 255 set to 0; this is because
// ristretto.sage does not mask the high bit of a field element. When the high bit is set,
// the ristretto.sage elligator implementation gives different results, since it takes a
// different field element as input.
let bytes: [[u8; 32]; 16] = [
[
184, 249, 135, 49, 253, 123, 89, 113, 67, 160, 6, 239, 7, 105, 211, 41, 192, 249,
185, 57, 9, 102, 70, 198, 15, 127, 7, 26, 160, 102, 134, 71,
],
[
229, 14, 241, 227, 75, 9, 118, 60, 128, 153, 226, 21, 183, 217, 91, 136, 98, 0,
231, 156, 124, 77, 82, 139, 142, 134, 164, 169, 169, 62, 250, 52,
],
[
115, 109, 36, 220, 180, 223, 99, 6, 204, 169, 19, 29, 169, 68, 84, 23, 21, 109,
189, 149, 127, 205, 91, 102, 172, 35, 112, 35, 134, 69, 186, 34,
],
[
16, 49, 96, 107, 171, 199, 164, 9, 129, 16, 64, 62, 241, 63, 132, 173, 209, 160,
112, 215, 105, 50, 157, 81, 253, 105, 1, 154, 229, 25, 120, 83,
],
[
156, 131, 161, 162, 236, 251, 5, 187, 167, 171, 17, 178, 148, 210, 90, 207, 86, 21,
79, 161, 167, 215, 234, 1, 136, 242, 182, 248, 38, 85, 79, 86,
],
[
251, 177, 124, 54, 18, 101, 75, 235, 245, 186, 19, 46, 133, 157, 229, 64, 10, 136,
181, 185, 78, 144, 254, 167, 137, 49, 107, 10, 61, 10, 21, 25,
],
[
232, 193, 20, 68, 240, 77, 186, 77, 183, 40, 44, 86, 150, 31, 198, 212, 76, 81, 3,
217, 197, 8, 126, 128, 126, 152, 164, 208, 153, 44, 189, 77,
],
[
173, 229, 149, 177, 37, 230, 30, 69, 61, 56, 172, 190, 219, 115, 167, 194, 71, 134,
59, 75, 28, 244, 118, 26, 162, 97, 64, 16, 15, 189, 30, 64,
],
[
106, 71, 61, 107, 250, 117, 42, 151, 91, 202, 212, 100, 52, 188, 190, 21, 125, 218,
31, 18, 253, 241, 160, 133, 57, 242, 3, 164, 189, 68, 111, 75,
],
[
112, 204, 182, 90, 220, 198, 120, 73, 173, 107, 193, 17, 227, 40, 162, 36, 150,
141, 235, 55, 172, 183, 12, 39, 194, 136, 43, 153, 244, 118, 91, 89,
],
[
111, 24, 203, 123, 254, 189, 11, 162, 51, 196, 163, 136, 204, 143, 10, 222, 33,
112, 81, 205, 34, 35, 8, 66, 90, 6, 164, 58, 170, 177, 34, 25,
],
[
225, 183, 30, 52, 236, 82, 6, 183, 109, 25, 227, 181, 25, 82, 41, 193, 80, 77, 161,
80, 242, 203, 79, 204, 136, 245, 131, 110, 237, 106, 3, 58,
],
[
207, 246, 38, 56, 30, 86, 176, 90, 27, 200, 61, 42, 221, 27, 56, 210, 79, 178, 189,
120, 68, 193, 120, 167, 77, 185, 53, 197, 124, 128, 191, 126,
],
[
1, 136, 215, 80, 240, 46, 63, 147, 16, 244, 230, 207, 82, 189, 74, 50, 106, 169,
138, 86, 30, 131, 214, 202, 166, 125, 251, 228, 98, 24, 36, 21,
],
[
210, 207, 228, 56, 155, 116, 207, 54, 84, 195, 251, 215, 249, 199, 116, 75, 109,
239, 196, 251, 194, 246, 252, 228, 70, 146, 156, 35, 25, 39, 241, 4,
],
[
34, 116, 123, 9, 8, 40, 93, 189, 9, 103, 57, 103, 66, 227, 3, 2, 157, 107, 134,
219, 202, 74, 230, 154, 78, 107, 219, 195, 214, 14, 84, 80,
],
];
let encoded_images: [CompressedRistretto; 16] = [
CompressedRistretto([
176, 157, 237, 97, 66, 29, 140, 166, 168, 94, 26, 157, 212, 216, 229, 160, 195,
246, 232, 239, 169, 112, 63, 193, 64, 32, 152, 69, 11, 190, 246, 86,
]),
CompressedRistretto([
234, 141, 77, 203, 181, 225, 250, 74, 171, 62, 15, 118, 78, 212, 150, 19, 131, 14,
188, 238, 194, 244, 141, 138, 166, 162, 83, 122, 228, 201, 19, 26,
]),
CompressedRistretto([
232, 231, 51, 92, 5, 168, 80, 36, 173, 179, 104, 68, 186, 149, 68, 40, 140, 170,
27, 103, 99, 140, 21, 242, 43, 62, 250, 134, 208, 255, 61, 89,
]),
CompressedRistretto([
208, 120, 140, 129, 177, 179, 237, 159, 252, 160, 28, 13, 206, 5, 211, 241, 192,
218, 1, 97, 130, 241, 20, 169, 119, 46, 246, 29, 79, 80, 77, 84,
]),
CompressedRistretto([
202, 11, 236, 145, 58, 12, 181, 157, 209, 6, 213, 88, 75, 147, 11, 119, 191, 139,
47, 142, 33, 36, 153, 193, 223, 183, 178, 8, 205, 120, 248, 110,
]),
CompressedRistretto([
26, 66, 231, 67, 203, 175, 116, 130, 32, 136, 62, 253, 215, 46, 5, 214, 166, 248,
108, 237, 216, 71, 244, 173, 72, 133, 82, 6, 143, 240, 104, 41,
]),
CompressedRistretto([
40, 157, 102, 96, 201, 223, 200, 197, 150, 181, 106, 83, 103, 126, 143, 33, 145,
230, 78, 6, 171, 146, 210, 143, 112, 5, 245, 23, 183, 138, 18, 120,
]),
CompressedRistretto([
220, 37, 27, 203, 239, 196, 176, 131, 37, 66, 188, 243, 185, 250, 113, 23, 167,
211, 154, 243, 168, 215, 54, 171, 159, 36, 195, 81, 13, 150, 43, 43,
]),
CompressedRistretto([
232, 121, 176, 222, 183, 196, 159, 90, 238, 193, 105, 52, 101, 167, 244, 170, 121,
114, 196, 6, 67, 152, 80, 185, 221, 7, 83, 105, 176, 208, 224, 121,
]),
CompressedRistretto([
226, 181, 183, 52, 241, 163, 61, 179, 221, 207, 220, 73, 245, 242, 25, 236, 67, 84,
179, 222, 167, 62, 167, 182, 32, 9, 92, 30, 165, 127, 204, 68,
]),
CompressedRistretto([
226, 119, 16, 242, 200, 139, 240, 87, 11, 222, 92, 146, 156, 243, 46, 119, 65, 59,
1, 248, 92, 183, 50, 175, 87, 40, 206, 53, 208, 220, 148, 13,
]),
CompressedRistretto([
70, 240, 79, 112, 54, 157, 228, 146, 74, 122, 216, 88, 232, 62, 158, 13, 14, 146,
115, 117, 176, 222, 90, 225, 244, 23, 94, 190, 150, 7, 136, 96,
]),
CompressedRistretto([
22, 71, 241, 103, 45, 193, 195, 144, 183, 101, 154, 50, 39, 68, 49, 110, 51, 44,
62, 0, 229, 113, 72, 81, 168, 29, 73, 106, 102, 40, 132, 24,
]),
CompressedRistretto([
196, 133, 107, 11, 130, 105, 74, 33, 204, 171, 133, 221, 174, 193, 241, 36, 38,
179, 196, 107, 219, 185, 181, 253, 228, 47, 155, 42, 231, 73, 41, 78,
]),
CompressedRistretto([
58, 255, 225, 197, 115, 208, 160, 143, 39, 197, 82, 69, 143, 235, 92, 170, 74, 40,
57, 11, 171, 227, 26, 185, 217, 207, 90, 185, 197, 190, 35, 60,
]),
CompressedRistretto([
88, 43, 92, 118, 223, 136, 105, 145, 238, 186, 115, 8, 214, 112, 153, 253, 38, 108,
205, 230, 157, 130, 11, 66, 101, 85, 253, 110, 110, 14, 148, 112,
]),
];
for i in 0..16 {
let r_0 = FieldElement::from_bytes(&bytes[i]);
let Q = RistrettoPoint::elligator_ristretto_flavor(&r_0);
assert_eq!(Q.compress(), encoded_images[i]);
}
}
// Known answer tests for the one-way mapping function in the Ristretto RFC
#[test]
fn one_way_map() {
// These inputs are from
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-04#appendix-A.3
let test_vectors: &[([u8; 64], CompressedRistretto)] = &[
(
[
0x5d, 0x1b, 0xe0, 0x9e, 0x3d, 0x0c, 0x82, 0xfc, 0x53, 0x81, 0x12, 0x49, 0x0e,
0x35, 0x70, 0x19, 0x79, 0xd9, 0x9e, 0x06, 0xca, 0x3e, 0x2b, 0x5b, 0x54, 0xbf,
0xfe, 0x8b, 0x4d, 0xc7, 0x72, 0xc1, 0x4d, 0x98, 0xb6, 0x96, 0xa1, 0xbb, 0xfb,
0x5c, 0xa3, 0x2c, 0x43, 0x6c, 0xc6, 0x1c, 0x16, 0x56, 0x37, 0x90, 0x30, 0x6c,
0x79, 0xea, 0xca, 0x77, 0x05, 0x66, 0x8b, 0x47, 0xdf, 0xfe, 0x5b, 0xb6,
],
CompressedRistretto([
0x30, 0x66, 0xf8, 0x2a, 0x1a, 0x74, 0x7d, 0x45, 0x12, 0x0d, 0x17, 0x40, 0xf1,
0x43, 0x58, 0x53, 0x1a, 0x8f, 0x04, 0xbb, 0xff, 0xe6, 0xa8, 0x19, 0xf8, 0x6d,
0xfe, 0x50, 0xf4, 0x4a, 0x0a, 0x46,
]),
),
(
[
0xf1, 0x16, 0xb3, 0x4b, 0x8f, 0x17, 0xce, 0xb5, 0x6e, 0x87, 0x32, 0xa6, 0x0d,
0x91, 0x3d, 0xd1, 0x0c, 0xce, 0x47, 0xa6, 0xd5, 0x3b, 0xee, 0x92, 0x04, 0xbe,
0x8b, 0x44, 0xf6, 0x67, 0x8b, 0x27, 0x01, 0x02, 0xa5, 0x69, 0x02, 0xe2, 0x48,
0x8c, 0x46, 0x12, 0x0e, 0x92, 0x76, 0xcf, 0xe5, 0x46, 0x38, 0x28, 0x6b, 0x9e,
0x4b, 0x3c, 0xdb, 0x47, 0x0b, 0x54, 0x2d, 0x46, 0xc2, 0x06, 0x8d, 0x38,
],
CompressedRistretto([
0xf2, 0x6e, 0x5b, 0x6f, 0x7d, 0x36, 0x2d, 0x2d, 0x2a, 0x94, 0xc5, 0xd0, 0xe7,
0x60, 0x2c, 0xb4, 0x77, 0x3c, 0x95, 0xa2, 0xe5, 0xc3, 0x1a, 0x64, 0xf1, 0x33,
0x18, 0x9f, 0xa7, 0x6e, 0xd6, 0x1b,
]),
),
(
[
0x84, 0x22, 0xe1, 0xbb, 0xda, 0xab, 0x52, 0x93, 0x8b, 0x81, 0xfd, 0x60, 0x2e,
0xff, 0xb6, 0xf8, 0x91, 0x10, 0xe1, 0xe5, 0x72, 0x08, 0xad, 0x12, 0xd9, 0xad,
0x76, 0x7e, 0x2e, 0x25, 0x51, 0x0c, 0x27, 0x14, 0x07, 0x75, 0xf9, 0x33, 0x70,
0x88, 0xb9, 0x82, 0xd8, 0x3d, 0x7f, 0xcf, 0x0b, 0x2f, 0xa1, 0xed, 0xff, 0xe5,
0x19, 0x52, 0xcb, 0xe7, 0x36, 0x5e, 0x95, 0xc8, 0x6e, 0xaf, 0x32, 0x5c,
],
CompressedRistretto([
0x00, 0x6c, 0xcd, 0x2a, 0x9e, 0x68, 0x67, 0xe6, 0xa2, 0xc5, 0xce, 0xa8, 0x3d,
0x33, 0x02, 0xcc, 0x9d, 0xe1, 0x28, 0xdd, 0x2a, 0x9a, 0x57, 0xdd, 0x8e, 0xe7,
0xb9, 0xd7, 0xff, 0xe0, 0x28, 0x26,
]),
),
(
[
0xac, 0x22, 0x41, 0x51, 0x29, 0xb6, 0x14, 0x27, 0xbf, 0x46, 0x4e, 0x17, 0xba,
0xee, 0x8d, 0xb6, 0x59, 0x40, 0xc2, 0x33, 0xb9, 0x8a, 0xfc, 0xe8, 0xd1, 0x7c,
0x57, 0xbe, 0xeb, 0x78, 0x76, 0xc2, 0x15, 0x0d, 0x15, 0xaf, 0x1c, 0xb1, 0xfb,
0x82, 0x4b, 0xbd, 0x14, 0x95, 0x5f, 0x2b, 0x57, 0xd0, 0x8d, 0x38, 0x8a, 0xab,
0x43, 0x1a, 0x39, 0x1c, 0xfc, 0x33, 0xd5, 0xba, 0xfb, 0x5d, 0xbb, 0xaf,
],
CompressedRistretto([
0xf8, 0xf0, 0xc8, 0x7c, 0xf2, 0x37, 0x95, 0x3c, 0x58, 0x90, 0xae, 0xc3, 0x99,
0x81, 0x69, 0x00, 0x5d, 0xae, 0x3e, 0xca, 0x1f, 0xbb, 0x04, 0x54, 0x8c, 0x63,
0x59, 0x53, 0xc8, 0x17, 0xf9, 0x2a,
]),
),
(
[
0x16, 0x5d, 0x69, 0x7a, 0x1e, 0xf3, 0xd5, 0xcf, 0x3c, 0x38, 0x56, 0x5b, 0xee,
0xfc, 0xf8, 0x8c, 0x0f, 0x28, 0x2b, 0x8e, 0x7d, 0xbd, 0x28, 0x54, 0x4c, 0x48,
0x34, 0x32, 0xf1, 0xce, 0xc7, 0x67, 0x5d, 0xeb, 0xea, 0x8e, 0xbb, 0x4e, 0x5f,
0xe7, 0xd6, 0xf6, 0xe5, 0xdb, 0x15, 0xf1, 0x55, 0x87, 0xac, 0x4d, 0x4d, 0x4a,
0x1d, 0xe7, 0x19, 0x1e, 0x0c, 0x1c, 0xa6, 0x66, 0x4a, 0xbc, 0xc4, 0x13,
],
CompressedRistretto([
0xae, 0x81, 0xe7, 0xde, 0xdf, 0x20, 0xa4, 0x97, 0xe1, 0x0c, 0x30, 0x4a, 0x76,
0x5c, 0x17, 0x67, 0xa4, 0x2d, 0x6e, 0x06, 0x02, 0x97, 0x58, 0xd2, 0xd7, 0xe8,
0xef, 0x7c, 0xc4, 0xc4, 0x11, 0x79,
]),
),
(
[
0xa8, 0x36, 0xe6, 0xc9, 0xa9, 0xca, 0x9f, 0x1e, 0x8d, 0x48, 0x62, 0x73, 0xad,
0x56, 0xa7, 0x8c, 0x70, 0xcf, 0x18, 0xf0, 0xce, 0x10, 0xab, 0xb1, 0xc7, 0x17,
0x2d, 0xdd, 0x60, 0x5d, 0x7f, 0xd2, 0x97, 0x98, 0x54, 0xf4, 0x7a, 0xe1, 0xcc,
0xf2, 0x04, 0xa3, 0x31, 0x02, 0x09, 0x5b, 0x42, 0x00, 0xe5, 0xbe, 0xfc, 0x04,
0x65, 0xac, 0xcc, 0x26, 0x31, 0x75, 0x48, 0x5f, 0x0e, 0x17, 0xea, 0x5c,
],
CompressedRistretto([
0xe2, 0x70, 0x56, 0x52, 0xff, 0x9f, 0x5e, 0x44, 0xd3, 0xe8, 0x41, 0xbf, 0x1c,
0x25, 0x1c, 0xf7, 0xdd, 0xdb, 0x77, 0xd1, 0x40, 0x87, 0x0d, 0x1a, 0xb2, 0xed,
0x64, 0xf1, 0xa9, 0xce, 0x86, 0x28,
]),
),
(
[
0x2c, 0xdc, 0x11, 0xea, 0xeb, 0x95, 0xda, 0xf0, 0x11, 0x89, 0x41, 0x7c, 0xdd,
0xdb, 0xf9, 0x59, 0x52, 0x99, 0x3a, 0xa9, 0xcb, 0x9c, 0x64, 0x0e, 0xb5, 0x05,
0x8d, 0x09, 0x70, 0x2c, 0x74, 0x62, 0x2c, 0x99, 0x65, 0xa6, 0x97, 0xa3, 0xb3,
0x45, 0xec, 0x24, 0xee, 0x56, 0x33, 0x5b, 0x55, 0x6e, 0x67, 0x7b, 0x30, 0xe6,
0xf9, 0x0a, 0xc7, 0x7d, 0x78, 0x10, 0x64, 0xf8, 0x66, 0xa3, 0xc9, 0x82,
],
CompressedRistretto([
0x80, 0xbd, 0x07, 0x26, 0x25, 0x11, 0xcd, 0xde, 0x48, 0x63, 0xf8, 0xa7, 0x43,
0x4c, 0xef, 0x69, 0x67, 0x50, 0x68, 0x1c, 0xb9, 0x51, 0x0e, 0xea, 0x55, 0x70,
0x88, 0xf7, 0x6d, 0x9e, 0x50, 0x65,
]),
),
(
[
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
CompressedRistretto([
0x30, 0x42, 0x82, 0x79, 0x10, 0x23, 0xb7, 0x31, 0x28, 0xd2, 0x77, 0xbd, 0xcb,
0x5c, 0x77, 0x46, 0xef, 0x2e, 0xac, 0x08, 0xdd, 0xe9, 0xf2, 0x98, 0x33, 0x79,
0xcb, 0x8e, 0x5e, 0xf0, 0x51, 0x7f,
]),
),
(
[
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
],
CompressedRistretto([
0x30, 0x42, 0x82, 0x79, 0x10, 0x23, 0xb7, 0x31, 0x28, 0xd2, 0x77, 0xbd, 0xcb,
0x5c, 0x77, 0x46, 0xef, 0x2e, 0xac, 0x08, 0xdd, 0xe9, 0xf2, 0x98, 0x33, 0x79,
0xcb, 0x8e, 0x5e, 0xf0, 0x51, 0x7f,
]),
),
(
[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
],
CompressedRistretto([
0x30, 0x42, 0x82, 0x79, 0x10, 0x23, 0xb7, 0x31, 0x28, 0xd2, 0x77, 0xbd, 0xcb,
0x5c, 0x77, 0x46, 0xef, 0x2e, 0xac, 0x08, 0xdd, 0xe9, 0xf2, 0x98, 0x33, 0x79,
0xcb, 0x8e, 0x5e, 0xf0, 0x51, 0x7f,
]),
),
(
[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
],
CompressedRistretto([
0x30, 0x42, 0x82, 0x79, 0x10, 0x23, 0xb7, 0x31, 0x28, 0xd2, 0x77, 0xbd, 0xcb,
0x5c, 0x77, 0x46, 0xef, 0x2e, 0xac, 0x08, 0xdd, 0xe9, 0xf2, 0x98, 0x33, 0x79,
0xcb, 0x8e, 0x5e, 0xf0, 0x51, 0x7f,
]),
),
];
// Check that onewaymap(input) == output for all the above vectors
for (input, output) in test_vectors {
let Q = RistrettoPoint::from_uniform_bytes(input);
assert_eq!(&Q.compress(), output);
}
}
#[test]
fn random_roundtrip() {
let mut rng = OsRng.unwrap_err();

View file

@ -1,4 +1,5 @@
import binascii
from hashlib import sha256
class InvalidEncodingException(Exception): pass
class NotOnCurveException(Exception): pass
class SpecException(Exception): pass
@ -6,7 +7,7 @@ class SpecException(Exception): pass
def lobit(x): return int(x) & 1
def hibit(x): return lobit(2*x)
def negative(x): return lobit(x)
def enc_le(x,n): return bytearray([int(x)>>(8*i) & 0xFF for i in xrange(n)])
def enc_le(x,n): return bytearray([int(x)>>(8*i) & 0xFF for i in range(n)])
def dec_le(x): return sum(b<<(8*i) for i,b in enumerate(x))
def randombytes(n): return bytearray([randint(0,255) for _ in range(n)])
@ -22,17 +23,17 @@ def optimized_version_of(spec):
try: opt_ans = f(self,*args,**kwargs),None
except Exception as e: opt_ans = None,e
if spec_ans[1] is None and opt_ans[1] is not None:
raise
raise opt_ans[1]
#raise SpecException("Mismatch in %s: spec returned %s but opt threw %s"
# % (f.__name__,str(spec_ans[0]),str(opt_ans[1])))
if spec_ans[1] is not None and opt_ans[1] is None:
raise
raise spec_ans[1]
#raise SpecException("Mismatch in %s: spec threw %s but opt returned %s"
# % (f.__name__,str(spec_ans[1]),str(opt_ans[0])))
if spec_ans[0] != opt_ans[0]:
raise SpecException("Mismatch in %s: %s != %s"
% (f.__name__,pr(spec_ans[0]),pr(opt_ans[0])))
if opt_ans[1] is not None: raise
if opt_ans[1] is not None: raise opt_ans[1]
else: return opt_ans[0]
wrapper.__name__ = f.__name__
return wrapper
@ -133,7 +134,7 @@ class QuotientEdwardsPoint(object):
s = dec_le(bytes)
if mustBeProper and s >= cls.F.order():
raise InvalidEncodingException("%d out of range!" % s)
bitlen = int(ceil(log(cls.F.order())/log(2)))
bitlen = cls.F.order().bit_length()
if maskHiBits: s &= 2^bitlen-1
s = cls.F(s)
if mustBePositive and negative(s):
@ -463,8 +464,8 @@ class Decaf_1_1_Point(QuotientEdwardsPoint):
if negative(sr) != toggle_r: sr = -sr
ret = self.gfToBytes(sr)
if self.elligator(ret) != self and self.elligator(ret) != -self:
print "WRONG!",[toggle_rotation,toggle_altx,toggle_s]
if self.elligator(ret) == -self and self != -self: print "Negated!",[toggle_rotation,toggle_altx,toggle_s]
print("WRONG!",[toggle_rotation,toggle_altx,toggle_s])
if self.elligator(ret) == -self and self != -self: print("Negated!",[toggle_rotation,toggle_altx,toggle_s])
rets.append(bytes(ret))
return rets
@ -590,7 +591,7 @@ class Decaf_1_1_Point(QuotientEdwardsPoint):
def elligatorInverseBruteForce(self):
"""Invert Elligator using SAGE's polynomial solver"""
a,d = self.a,self.d
R.<r0> = self.F[]
R = self.F["r0"]
r = self.qnr * r0^2
den = (d*r-(d-a))*((d-a)*r-d)
n1 = (r+1)*(a-2*d)/den
@ -602,7 +603,7 @@ class Decaf_1_1_Point(QuotientEdwardsPoint):
y = (1-a*s2) / t
selfT = self
for i in xrange(self.cofactor/2):
for i in range(self.cofactor/2):
xT,yT = selfT
polyX = xT^2-x2
polyY = yT-y
@ -721,7 +722,7 @@ class IsoEd25519Point(Decaf_1_1_Point):
class TestFailedException(Exception): pass
def test(cls,n):
print "Testing curve %s" % cls.__name__
print("Testing curve %s" % cls.__name__)
specials = [1]
ii = cls.F(-1)
@ -744,7 +745,7 @@ def test(cls,n):
P = cls.base()
Q = cls()
for i in xrange(n):
for i in range(n):
#print binascii.hexlify(Q.encode())
QE = Q.encode()
QQ = cls.decode(QE)
@ -766,7 +767,7 @@ def test(cls,n):
raise TestFailedException("s -> 1/s should work for cofactor 4")
QT = Q
for h in xrange(cls.cofactor):
for h in range(cls.cofactor):
QT = QT.torque()
if QT.encode() != QE:
raise TestFailedException("Can't torque %s,%d" % (str(Q),h+1))
@ -782,19 +783,19 @@ def test(cls,n):
Q = Q1
def testElligator(cls,n):
print "Testing elligator on %s" % cls.__name__
for i in xrange(n):
print("Testing elligator on %s" % cls.__name__)
for i in range(n):
r = randombytes(cls.encLen)
P = cls.elligator(r)
if hasattr(P,"invertElligator"):
iv = P.invertElligator()
modr = bytes(cls.gfToBytes(cls.bytesToGf(r,mustBeProper=False,maskHiBits=True)))
iv2 = P.torque().invertElligator()
if modr not in iv: print "Failed to invert Elligator!"
if modr not in iv: print("Failed to invert Elligator!")
if len(iv) != len(set(iv)):
print "Elligator inverses not unique!", len(set(iv)), len(iv)
print("Elligator inverses not unique!", len(set(iv)), len(iv))
if iv != iv2:
print "Elligator is untorqueable!"
print("Elligator is untorqueable!")
#print [binascii.hexlify(j) for j in iv]
#print [binascii.hexlify(j) for j in iv2]
#break
@ -802,7 +803,7 @@ def testElligator(cls,n):
pass # TODO
def gangtest(classes,n):
print "Gang test",[cls.__name__ for cls in classes]
print("Gang test",[cls.__name__ for cls in classes])
specials = [1]
ii = classes[0].F(-1)
while is_square(ii):
@ -810,32 +811,54 @@ def gangtest(classes,n):
ii = sqrt(ii)
specials.append(ii)
for i in xrange(n):
for i in range(n):
rets = [bytes((cls.base()*i).encode()) for cls in classes]
if len(set(rets)) != 1:
print "Divergence in encode at %d" % i
print("Divergence in encode at %d" % i)
for c,ret in zip(classes,rets):
print c,binascii.hexlify(ret)
print
print(c,binascii.hexlify(ret))
print()
if i < len(specials): r0 = enc_le(specials[i],classes[0].encLen)
else: r0 = randombytes(classes[0].encLen)
rets = [bytes((cls.elligator(r0)*i).encode()) for cls in classes]
if len(set(rets)) != 1:
print "Divergence in elligator at %d" % i
print("Divergence in elligator at %d" % i)
for c,ret in zip(classes,rets):
print c,binascii.hexlify(ret)
print
print(c,binascii.hexlify(ret))
print()
def testDoubleAndEncode(cls,n):
print "Testing doubleAndEncode on %s" % cls.__name__
for i in xrange(n):
print("Testing doubleAndEncode on %s" % cls.__name__)
for i in range(n):
r1 = randombytes(cls.encLen)
r2 = randombytes(cls.encLen)
u = cls.elligator(r1) + cls.elligator(r2)
u.doubleAndEncode()
# Prints test vectors for the Lizard encoding function. Output is the encoding of a compressed
# Ristretto point
def testLizard():
# 16-byte strings, in hex
inputs = [
"00000000000000000000000000000000",
"01010101010101010101010101010101",
"000102030405060708090a0b0c0d0e0f",
"dddddddddddddddddddddddddddddddd",
]
for payload in map(binascii.unhexlify, inputs):
# Do the lizard encoding of the field element
data = bytearray(sha256(payload).digest())
data[8:24] = payload
data[0] &= 0b11111110
data[31] &= 0b00111111
# Encode to Ristretto (Ed25519Point is actually Ristretto), and print the byte repr
pt = Ed25519Point.elligator(data)
print("lizard({}) = {}".format(binascii.hexlify(payload), binascii.hexlify(pt.encode())))
testDoubleAndEncode(Ed25519Point,100)
testDoubleAndEncode(NegEd25519Point,100)
testDoubleAndEncode(IsoEd25519Point,100)
@ -853,5 +876,6 @@ testDoubleAndEncode(TwistedEd448GoldilocksPoint,100)
#testElligator(IsoEd448Point,100)
#testElligator(Ed448GoldilocksPoint,100)
#testElligator(TwistedEd448GoldilocksPoint,100)
#testLizard()
#gangtest([IsoEd448Point,TwistedEd448GoldilocksPoint,Ed448GoldilocksPoint],100)
#gangtest([Ed25519Point,IsoEd25519Point],100)