ed25519_dalek/signature.rs
1// -*- mode: rust; -*-
2//
3// This file is part of ed25519-dalek.
4// Copyright (c) 2017-2019 isis lovecruft
5// See LICENSE for licensing information.
6//
7// Authors:
8// - isis agora lovecruft <[email protected]>
9
10//! An ed25519 signature.
11
12use core::fmt::Debug;
13
14use curve25519_dalek::edwards::CompressedEdwardsY;
15use curve25519_dalek::scalar::Scalar;
16
17use crate::constants::*;
18use crate::errors::*;
19
20/// An ed25519 signature.
21///
22/// # Note
23///
24/// These signatures, unlike the ed25519 signature reference implementation, are
25/// "detached"—that is, they do **not** include a copy of the message which has
26/// been signed.
27#[allow(non_snake_case)]
28#[derive(Copy, Eq, PartialEq)]
29pub(crate) struct InternalSignature {
30 /// `R` is an `EdwardsPoint`, formed by using an hash function with
31 /// 512-bits output to produce the digest of:
32 ///
33 /// - the nonce half of the `ExpandedSecretKey`, and
34 /// - the message to be signed.
35 ///
36 /// This digest is then interpreted as a `Scalar` and reduced into an
37 /// element in ℤ/lℤ. The scalar is then multiplied by the distinguished
38 /// basepoint to produce `R`, and `EdwardsPoint`.
39 pub(crate) R: CompressedEdwardsY,
40
41 /// `s` is a `Scalar`, formed by using an hash function with 512-bits output
42 /// to produce the digest of:
43 ///
44 /// - the `r` portion of this `Signature`,
45 /// - the `PublicKey` which should be used to verify this `Signature`, and
46 /// - the message to be signed.
47 ///
48 /// This digest is then interpreted as a `Scalar` and reduced into an
49 /// element in ℤ/lℤ.
50 pub(crate) s: Scalar,
51}
52
53impl Clone for InternalSignature {
54 fn clone(&self) -> Self {
55 *self
56 }
57}
58
59impl Debug for InternalSignature {
60 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
61 write!(f, "Signature( R: {:?}, s: {:?} )", &self.R, &self.s)
62 }
63}
64
65/// Ensures that the scalar `s` of a signature is within the bounds [0, 2^253).
66///
67/// **Unsafe**: This version of `check_scalar` permits signature malleability. See README.
68#[cfg(feature = "legacy_compatibility")]
69#[inline(always)]
70fn check_scalar(bytes: [u8; 32]) -> Result<Scalar, SignatureError> {
71 // The highest 3 bits must not be set. No other checking for the
72 // remaining 2^253 - 2^252 + 27742317777372353535851937790883648493
73 // potential non-reduced scalars is performed.
74 //
75 // This is compatible with ed25519-donna and libsodium when
76 // `-D ED25519_COMPAT` is NOT specified.
77 if bytes[31] & 224 != 0 {
78 return Err(InternalError::ScalarFormat.into());
79 }
80
81 // You cannot do arithmetic with scalars construct with Scalar::from_bits. We only use this
82 // scalar for EdwardsPoint::vartime_double_scalar_mul_basepoint, which is an accepted usecase.
83 Ok(Scalar::from_bits(bytes))
84}
85
86/// Ensures that the scalar `s` of a signature is within the bounds [0, ℓ)
87#[cfg(not(feature = "legacy_compatibility"))]
88#[inline(always)]
89fn check_scalar(bytes: [u8; 32]) -> Result<Scalar, SignatureError> {
90 match Scalar::from_canonical_bytes(bytes).into() {
91 None => Err(InternalError::ScalarFormat.into()),
92 Some(x) => Ok(x),
93 }
94}
95
96impl InternalSignature {
97 /// Construct a `Signature` from a slice of bytes.
98 ///
99 /// # Scalar Malleability Checking
100 ///
101 /// As originally specified in the ed25519 paper (cf. the "Malleability"
102 /// section of the README in this repo), no checks whatsoever were performed
103 /// for signature malleability.
104 ///
105 /// Later, a semi-functional, hacky check was added to most libraries to
106 /// "ensure" that the scalar portion, `s`, of the signature was reduced `mod
107 /// \ell`, the order of the basepoint:
108 ///
109 /// ```ignore
110 /// if signature.s[31] & 224 != 0 {
111 /// return Err();
112 /// }
113 /// ```
114 ///
115 /// This bit-twiddling ensures that the most significant three bits of the
116 /// scalar are not set:
117 ///
118 /// ```python,ignore
119 /// >>> 0b00010000 & 224
120 /// 0
121 /// >>> 0b00100000 & 224
122 /// 32
123 /// >>> 0b01000000 & 224
124 /// 64
125 /// >>> 0b10000000 & 224
126 /// 128
127 /// ```
128 ///
129 /// However, this check is hacky and insufficient to check that the scalar is
130 /// fully reduced `mod \ell = 2^252 + 27742317777372353535851937790883648493` as
131 /// it leaves us with a guanteed bound of 253 bits. This means that there are
132 /// `2^253 - 2^252 + 2774231777737235353585193779088364849311` remaining scalars
133 /// which could cause malleabilllity.
134 ///
135 /// RFC8032 [states](https://tools.ietf.org/html/rfc8032#section-5.1.7):
136 ///
137 /// > To verify a signature on a message M using public key A, [...]
138 /// > first split the signature into two 32-octet halves. Decode the first
139 /// > half as a point R, and the second half as an integer S, in the range
140 /// > 0 <= s < L. Decode the public key A as point A'. If any of the
141 /// > decodings fail (including S being out of range), the signature is
142 /// > invalid.
143 ///
144 /// However, by the time this was standardised, most libraries in use were
145 /// only checking the most significant three bits. (See also the
146 /// documentation for [`crate::VerifyingKey::verify_strict`].)
147 #[inline]
148 #[allow(non_snake_case)]
149 pub fn from_bytes(bytes: &[u8; SIGNATURE_LENGTH]) -> Result<InternalSignature, SignatureError> {
150 // TODO: Use bytes.split_array_ref once it’s in MSRV.
151 let mut R_bytes: [u8; 32] = [0u8; 32];
152 let mut s_bytes: [u8; 32] = [0u8; 32];
153 R_bytes.copy_from_slice(&bytes[00..32]);
154 s_bytes.copy_from_slice(&bytes[32..64]);
155
156 Ok(InternalSignature {
157 R: CompressedEdwardsY(R_bytes),
158 s: check_scalar(s_bytes)?,
159 })
160 }
161}
162
163impl TryFrom<&ed25519::Signature> for InternalSignature {
164 type Error = SignatureError;
165
166 fn try_from(sig: &ed25519::Signature) -> Result<InternalSignature, SignatureError> {
167 InternalSignature::from_bytes(&sig.to_bytes())
168 }
169}
170
171impl From<InternalSignature> for ed25519::Signature {
172 fn from(sig: InternalSignature) -> ed25519::Signature {
173 ed25519::Signature::from_components(*sig.R.as_bytes(), *sig.s.as_bytes())
174 }
175}