1use base64ct::{Base64Unpadded, Encoding as _};
13use curve25519_dalek::Scalar;
14use derive_deftly::Deftly;
15use safelog::util::write_start_redacted;
16use std::fmt::{self, Debug, Display, Formatter};
17use subtle::{Choice, ConstantTimeEq};
18
19#[cfg(feature = "memquota-memcost")]
20use tor_memquota_cost::derive_deftly_template_HasMemoryCost;
21
22use ed25519_dalek::hazmat::ExpandedSecretKey;
23use ed25519_dalek::{Signer as _, Verifier as _};
24
25use crate::util::ct::{
26 CtByteArray, derive_deftly_template_ConstantTimeEq, derive_deftly_template_PartialEqFromCtEq,
27};
28
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub struct Signature(pub(crate) ed25519_dalek::Signature);
34
35#[derive(Debug, Deftly)]
41#[derive_deftly(ConstantTimeEq)]
42pub struct Keypair(pub(crate) ed25519_dalek::SigningKey);
43
44#[derive(Clone, Copy, Debug, Eq, Deftly)]
48#[derive_deftly(PartialEqFromCtEq)]
49pub struct PublicKey(pub(crate) ed25519_dalek::VerifyingKey);
50
51impl<'a> From<&'a Keypair> for PublicKey {
52 fn from(value: &'a Keypair) -> Self {
53 PublicKey((&value.0).into())
54 }
55}
56
57impl ConstantTimeEq for PublicKey {
58 fn ct_eq(&self, other: &Self) -> Choice {
59 self.as_bytes().ct_eq(other.as_bytes())
60 }
61}
62
63impl PublicKey {
64 pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, signature::Error> {
66 Ok(PublicKey(ed25519_dalek::VerifyingKey::from_bytes(bytes)?))
67 }
68
69 pub fn as_bytes(&self) -> &[u8; 32] {
71 self.0.as_bytes()
72 }
73 pub fn to_bytes(&self) -> [u8; 32] {
75 self.0.to_bytes()
76 }
77 pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), signature::Error> {
81 self.0.verify(message, &signature.0)
82 }
83}
84impl Keypair {
85 pub fn generate<R: rand_core::Rng + rand_core::CryptoRng>(csprng: &mut R) -> Self {
87 Self(ed25519_dalek::SigningKey::generate(csprng))
88 }
89 pub fn from_bytes(bytes: &[u8; 32]) -> Self {
91 Self(ed25519_dalek::SigningKey::from_bytes(bytes))
92 }
93 pub fn as_bytes(&self) -> &[u8; 32] {
95 self.0.as_bytes()
96 }
97 pub fn to_bytes(&self) -> [u8; 32] {
99 self.0.to_bytes()
100 }
101 pub fn verifying_key(&self) -> PublicKey {
103 PublicKey(*self.0.as_ref())
104 }
105 pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), signature::Error> {
107 self.0.verify(message, &signature.0)
108 }
109 pub fn sign(&self, message: &[u8]) -> Signature {
111 Signature(self.0.sign(message))
112 }
113}
114impl Signature {
115 pub fn from_bytes(bytes: &[u8; 64]) -> Self {
117 Self(ed25519_dalek::Signature::from_bytes(bytes))
118 }
119 pub fn to_bytes(&self) -> [u8; 64] {
121 self.0.to_bytes()
122 }
123}
124impl<'a> TryFrom<&'a [u8]> for PublicKey {
125 type Error = signature::Error;
126
127 fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
128 Ok(Self(ed25519_dalek::VerifyingKey::try_from(value)?))
129 }
130}
131impl<'a> From<&'a [u8; 32]> for Keypair {
132 fn from(value: &'a [u8; 32]) -> Self {
133 Self(ed25519_dalek::SigningKey::from(value))
134 }
135}
136impl From<[u8; 64]> for Signature {
137 fn from(value: [u8; 64]) -> Self {
138 Signature(value.into())
139 }
140}
141impl<'a> From<&'a [u8; 64]> for Signature {
142 fn from(value: &'a [u8; 64]) -> Self {
143 Signature(value.into())
144 }
145}
146
147pub const ED25519_ID_LEN: usize = 32;
149
150pub const ED25519_SIGNATURE_LEN: usize = 64;
152
153#[allow(clippy::exhaustive_structs)]
161#[derive(Deftly)]
162#[derive_deftly(ConstantTimeEq)]
163pub struct ExpandedKeypair {
164 pub(crate) secret: ExpandedSecretKey,
166 pub(crate) public: PublicKey,
173}
174
175impl ExpandedKeypair {
176 pub fn public(&self) -> &PublicKey {
178 &self.public
179 }
180
181 pub fn sign(&self, message: &[u8]) -> Signature {
187 use sha2::Sha512;
188 Signature(ed25519_dalek::hazmat::raw_sign::<Sha512>(
190 &self.secret,
191 message,
192 &self.public.0,
193 ))
194 }
195
196 pub fn to_secret_key_bytes(&self) -> [u8; 64] {
201 let mut output = [0_u8; 64];
202 output[0..32].copy_from_slice(&self.secret.scalar.to_bytes());
203 output[32..64].copy_from_slice(&self.secret.hash_prefix);
204 output
205 }
206
207 pub fn from_secret_key_bytes(bytes: [u8; 64]) -> Option<Self> {
214 let scalar = Option::from(Scalar::from_bytes_mod_order(
215 bytes[0..32].try_into().expect("wrong length on slice"),
216 ))?;
217 let hash_prefix = bytes[32..64].try_into().expect("wrong length on slice");
218 let secret = ExpandedSecretKey {
219 scalar,
220 hash_prefix,
221 };
222 let public = PublicKey((&secret).into());
223 Some(Self { secret, public })
224 }
225
226 }
230
231impl<'a> From<&'a Keypair> for ExpandedKeypair {
232 fn from(kp: &'a Keypair) -> ExpandedKeypair {
233 ExpandedKeypair {
234 secret: kp.as_bytes().into(),
235 public: kp.into(),
236 }
237 }
238}
239
240impl From<ExpandedKeypair> for PublicKey {
241 fn from(ekp: ExpandedKeypair) -> PublicKey {
242 ekp.public
243 }
244}
245
246#[derive(Clone, Copy, Hash, PartialOrd, Ord, Eq, PartialEq)]
259#[cfg_attr(
260 feature = "memquota-memcost",
261 derive(Deftly),
262 derive_deftly(HasMemoryCost)
263)]
264pub struct Ed25519Identity {
265 id: CtByteArray<ED25519_ID_LEN>,
267}
268
269impl Ed25519Identity {
270 pub fn new(id: [u8; 32]) -> Self {
288 Ed25519Identity { id: id.into() }
289 }
290 pub fn from_bytes(id: &[u8]) -> Option<Self> {
292 Some(Ed25519Identity::new(id.try_into().ok()?))
293 }
294 pub fn as_bytes(&self) -> &[u8] {
296 &self.id.as_ref()[..]
297 }
298 pub fn from_base64(s: &str) -> Option<Self> {
303 let bytes = Base64Unpadded::decode_vec(s).ok()?;
304 Ed25519Identity::from_bytes(&bytes)
305 }
306}
307
308impl From<[u8; ED25519_ID_LEN]> for Ed25519Identity {
309 fn from(id: [u8; ED25519_ID_LEN]) -> Self {
310 Ed25519Identity::new(id)
311 }
312}
313
314impl From<Ed25519Identity> for [u8; ED25519_ID_LEN] {
315 fn from(value: Ed25519Identity) -> Self {
316 value.id.into()
317 }
318}
319
320impl From<PublicKey> for Ed25519Identity {
321 fn from(pk: PublicKey) -> Self {
322 (&pk).into()
323 }
324}
325
326impl From<&PublicKey> for Ed25519Identity {
327 fn from(pk: &PublicKey) -> Self {
328 Ed25519Identity::from_bytes(pk.as_bytes()).expect("Ed25519 public key had wrong length?")
331 }
332}
333
334impl TryFrom<&Ed25519Identity> for PublicKey {
335 type Error = ed25519_dalek::SignatureError;
336 fn try_from(id: &Ed25519Identity) -> Result<PublicKey, Self::Error> {
337 PublicKey::from_bytes(id.id.as_ref())
338 }
339}
340
341impl TryFrom<Ed25519Identity> for PublicKey {
342 type Error = ed25519_dalek::SignatureError;
343 fn try_from(id: Ed25519Identity) -> Result<PublicKey, Self::Error> {
344 (&id).try_into()
345 }
346}
347
348impl ConstantTimeEq for Ed25519Identity {
349 fn ct_eq(&self, other: &Self) -> Choice {
350 self.id.ct_eq(&other.id)
351 }
352}
353
354impl Display for Ed25519Identity {
355 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
356 write!(f, "{}", Base64Unpadded::encode_string(self.id.as_ref()))
357 }
358}
359
360impl Debug for Ed25519Identity {
361 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
362 write!(f, "Ed25519Identity {{ {} }}", self)
363 }
364}
365
366impl safelog::Redactable for Ed25519Identity {
367 fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
370 write_start_redacted(f, &Base64Unpadded::encode_string(self.id.as_ref()), 2, "…")
371 }
372
373 fn debug_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374 write!(f, "Ed25519Identity {{ {} }}", self.redacted())
375 }
376}
377
378impl serde::Serialize for Ed25519Identity {
379 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
380 where
381 S: serde::Serializer,
382 {
383 if serializer.is_human_readable() {
384 serializer.serialize_str(&Base64Unpadded::encode_string(self.id.as_ref()))
385 } else {
386 serializer.serialize_bytes(&self.id.as_ref()[..])
387 }
388 }
389}
390
391impl<'de> serde::Deserialize<'de> for Ed25519Identity {
392 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
393 where
394 D: serde::Deserializer<'de>,
395 {
396 if deserializer.is_human_readable() {
397 struct EdIdentityVisitor;
399 impl<'de> serde::de::Visitor<'de> for EdIdentityVisitor {
400 type Value = Ed25519Identity;
401 fn expecting(&self, fmt: &mut std::fmt::Formatter<'_>) -> fmt::Result {
402 fmt.write_str("base64-encoded Ed25519 public key")
403 }
404 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
405 where
406 E: serde::de::Error,
407 {
408 let bytes = Base64Unpadded::decode_vec(s).map_err(E::custom)?;
409 Ed25519Identity::from_bytes(&bytes)
410 .ok_or_else(|| E::custom("wrong length for Ed25519 public key"))
411 }
412 }
413
414 deserializer.deserialize_str(EdIdentityVisitor)
415 } else {
416 struct EdIdentityVisitor;
418 impl<'de> serde::de::Visitor<'de> for EdIdentityVisitor {
419 type Value = Ed25519Identity;
420 fn expecting(&self, fmt: &mut std::fmt::Formatter<'_>) -> fmt::Result {
421 fmt.write_str("ed25519 public key")
422 }
423 fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>
424 where
425 E: serde::de::Error,
426 {
427 Ed25519Identity::from_bytes(bytes)
428 .ok_or_else(|| E::custom("wrong length for ed25519 public key"))
429 }
430 }
431 deserializer.deserialize_bytes(EdIdentityVisitor)
432 }
433 }
434}
435
436#[derive(Clone, Debug)]
439#[cfg_attr(
440 feature = "memquota-memcost",
441 derive(Deftly),
442 derive_deftly(HasMemoryCost)
443)]
444pub struct ValidatableEd25519Signature {
445 #[cfg_attr(feature = "memquota-memcost", deftly(has_memory_cost(copy)))]
447 key: PublicKey,
448 #[cfg_attr(feature = "memquota-memcost", deftly(has_memory_cost(copy)))]
450 sig: Signature,
451 entire_text_of_signed_thing: Vec<u8>,
459}
460
461impl ValidatableEd25519Signature {
462 pub fn new(key: PublicKey, sig: Signature, text: &[u8]) -> Self {
464 ValidatableEd25519Signature {
465 key,
466 sig,
467 entire_text_of_signed_thing: text.into(),
468 }
469 }
470
471 pub(crate) fn as_parts(&self) -> (&PublicKey, &Signature, &[u8]) {
473 (&self.key, &self.sig, &self.entire_text_of_signed_thing[..])
474 }
475
476 pub fn signature(&self) -> &Signature {
478 &self.sig
479 }
480}
481
482impl super::ValidatableSignature for ValidatableEd25519Signature {
483 fn is_valid(&self) -> bool {
484 self.key
485 .verify(&self.entire_text_of_signed_thing[..], &self.sig)
486 .is_ok()
487 }
488
489 fn as_ed25519(&self) -> Option<&ValidatableEd25519Signature> {
490 Some(self)
491 }
492}
493
494pub fn validate_batch(sigs: &[&ValidatableEd25519Signature]) -> bool {
506 use crate::pk::ValidatableSignature;
507 if sigs.is_empty() {
508 true
511 } else if sigs.len() == 1 {
512 sigs[0].is_valid()
514 } else {
515 let mut ed_msgs = Vec::new();
516 let mut ed_sigs = Vec::new();
517 let mut ed_pks = Vec::new();
518 for ed_sig in sigs {
519 let (pk, sig, msg) = ed_sig.as_parts();
520 ed_sigs.push(sig.0);
521 ed_pks.push(pk.0);
522 ed_msgs.push(msg);
523 }
524 ed25519_dalek::verify_batch(&ed_msgs[..], &ed_sigs[..], &ed_pks[..]).is_ok()
525 }
526}
527
528pub trait Ed25519PublicKey {
530 fn public_key(&self) -> PublicKey;
532}
533
534impl Ed25519PublicKey for Keypair {
535 fn public_key(&self) -> PublicKey {
536 Keypair::verifying_key(self)
537 }
538}
539
540impl Ed25519PublicKey for ExpandedKeypair {
541 fn public_key(&self) -> PublicKey {
542 self.public
543 }
544}
545
546pub trait Ed25519SigningKey {
548 fn sign(&self, message: &[u8]) -> Signature;
550}
551
552impl Ed25519SigningKey for Keypair {
553 fn sign(&self, message: &[u8]) -> Signature {
554 Keypair::sign(self, message)
555 }
556}
557impl Ed25519SigningKey for ExpandedKeypair {
558 fn sign(&self, message: &[u8]) -> Signature {
559 ExpandedKeypair::sign(self, message)
560 }
561}
562
563#[cfg(test)]
564mod test {
565 #![allow(clippy::bool_assert_comparison)]
567 #![allow(clippy::clone_on_copy)]
568 #![allow(clippy::dbg_macro)]
569 #![allow(clippy::mixed_attributes_style)]
570 #![allow(clippy::print_stderr)]
571 #![allow(clippy::print_stdout)]
572 #![allow(clippy::single_char_pattern)]
573 #![allow(clippy::unwrap_used)]
574 #![allow(clippy::unchecked_time_subtraction)]
575 #![allow(clippy::useless_vec)]
576 #![allow(clippy::needless_pass_by_value)]
577 #![allow(clippy::string_slice)] use super::*;
581
582 #[test]
583 fn ed_from_base64() {
584 let id =
585 Ed25519Identity::from_base64("qpL/LxLYVEXghU76iG3LsSI/UW7MBpIROZK0AB18560").unwrap();
586
587 assert_eq!(
588 id,
589 Ed25519Identity::from([
590 0xaa, 0x92, 0xff, 0x2f, 0x12, 0xd8, 0x54, 0x45, 0xe0, 0x85, 0x4e, 0xfa, 0x88, 0x6d,
591 0xcb, 0xb1, 0x22, 0x3f, 0x51, 0x6e, 0xcc, 0x06, 0x92, 0x11, 0x39, 0x92, 0xb4, 0x00,
592 0x1d, 0x7c, 0xe7, 0xad
593 ]),
594 );
595 }
596}