1use std::fmt::{self, Debug, Display};
8use std::str::FromStr;
9
10use derive_deftly::Deftly;
11use digest::Digest;
12use itertools::{Itertools, chain};
13use safelog::DisplayRedacted;
14use subtle::ConstantTimeEq;
15use thiserror::Error;
16use tor_basic_utils::{StrExt as _, impl_debug_hex};
17use tor_key_forge::ToEncodableKey;
18use tor_llcrypto::d::Sha3_256;
19use tor_llcrypto::pk::ed25519::{Ed25519PublicKey, Ed25519SigningKey};
20use tor_llcrypto::pk::{curve25519, ed25519, keymanip};
21use tor_llcrypto::util::ct::CtByteArray;
22use tor_llcrypto::{
23 derive_deftly_template_ConstantTimeEq, derive_deftly_template_PartialEqFromCtEq,
24};
25
26use crate::macros::{define_bytes, define_pk_keypair};
27use crate::time::TimePeriod;
28
29#[allow(deprecated)]
30pub use hs_client_intro_auth::{HsClientIntroAuthKey, HsClientIntroAuthKeypair};
31
32define_bytes! {
33#[derive(Copy, Clone, Eq, PartialEq, Hash)]
45pub struct HsId([u8; 32]);
46}
47
48define_pk_keypair! {
49#[derive(Deftly)]
63#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
64pub struct HsIdKey(ed25519::PublicKey) /
65 #[derive(Deftly)]
79 #[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
80 HsIdKeypair(ed25519::ExpandedKeypair);
81}
82
83impl HsIdKey {
84 pub fn id(&self) -> HsId {
88 HsId(self.0.to_bytes().into())
89 }
90}
91impl TryFrom<HsId> for HsIdKey {
92 type Error = signature::Error;
93
94 fn try_from(value: HsId) -> Result<Self, Self::Error> {
95 ed25519::PublicKey::from_bytes(value.0.as_ref()).map(HsIdKey)
96 }
97}
98impl From<HsIdKey> for HsId {
99 fn from(value: HsIdKey) -> Self {
100 value.id()
101 }
102}
103
104impl From<&HsIdKeypair> for HsIdKey {
105 fn from(value: &HsIdKeypair) -> Self {
106 Self(*value.0.public())
107 }
108}
109
110impl From<HsIdKeypair> for HsIdKey {
111 fn from(value: HsIdKeypair) -> Self {
112 Self(*value.0.public())
113 }
114}
115
116const HSID_ONION_VERSION: u8 = 0x03;
118
119pub const HSID_ONION_SUFFIX: &str = ".onion";
121
122impl safelog::DisplayRedacted for HsId {
123 fn fmt_unredacted(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
124 let checksum = self.onion_checksum();
126 let binary = chain!(self.0.as_ref(), &checksum, &[HSID_ONION_VERSION],)
127 .cloned()
128 .collect_vec();
129 let mut b32 = data_encoding::BASE32_NOPAD.encode(&binary);
130 b32.make_ascii_lowercase();
131 write!(f, "{}{}", b32, HSID_ONION_SUFFIX)
132 }
133
134 fn fmt_redacted(&self, f: &mut fmt::Formatter) -> fmt::Result {
138 let unredacted = self.display_unredacted().to_string();
139 const DATA: usize = 56;
141 assert_eq!(unredacted.len(), DATA + HSID_ONION_SUFFIX.len());
142
143 write!(f, "[…]{}", &unredacted[DATA - 3..])
152 }
153}
154
155impl safelog::DebugRedacted for HsId {
156 fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 write!(f, "HsId({})", self.display_redacted())
158 }
159
160 fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161 write!(f, "HsId({})", self.display_unredacted())
162 }
163}
164
165safelog::derive_redacted_debug!(HsId);
166
167impl FromStr for HsId {
168 type Err = HsIdParseError;
169 fn from_str(s: &str) -> Result<Self, HsIdParseError> {
170 use HsIdParseError as PE;
171
172 let s = s
173 .strip_suffix_ignore_ascii_case(HSID_ONION_SUFFIX)
174 .ok_or(PE::NotOnionDomain)?;
175
176 if s.contains('.') {
177 return Err(PE::HsIdContainsSubdomain);
178 }
179
180 let mut s = s.to_owned();
186 s.make_ascii_uppercase();
187
188 let binary = data_encoding::BASE32_NOPAD.decode(s.as_bytes())?;
193 let mut binary = tor_bytes::Reader::from_slice(&binary);
194
195 let pubkey: [u8; 32] = binary.extract()?;
196 let checksum: [u8; 2] = binary.extract()?;
197 let version: u8 = binary.extract()?;
198 let tentative = HsId(pubkey.into());
199
200 if version != HSID_ONION_VERSION {
202 return Err(PE::UnsupportedVersion(version));
203 }
204 if checksum != tentative.onion_checksum() {
205 return Err(PE::WrongChecksum);
206 }
207 Ok(tentative)
208 }
209}
210
211#[derive(Error, Clone, Debug)]
213#[non_exhaustive]
214pub enum HsIdParseError {
215 #[error("Domain name does not end in .onion")]
217 NotOnionDomain,
218
219 #[error("Invalid base32 in .onion address")]
223 InvalidBase32(#[from] data_encoding::DecodeError),
224
225 #[error("Invalid encoded binary data in .onion address")]
227 InvalidData(#[from] tor_bytes::Error),
228
229 #[error("Unsupported .onion address version, v{0}")]
231 UnsupportedVersion(u8),
232
233 #[error("Checksum failed, .onion address corrupted")]
235 WrongChecksum,
236
237 #[error("`.onion` address with subdomain passed where not expected")]
239 HsIdContainsSubdomain,
240}
241
242impl HsId {
243 fn onion_checksum(&self) -> [u8; 2] {
245 let mut h = Sha3_256::new();
246 h.update(b".onion checksum");
247 h.update(self.0.as_ref());
248 h.update([HSID_ONION_VERSION]);
249 h.finalize()[..2]
250 .try_into()
251 .expect("slice of fixed size wasn't that size")
252 }
253}
254
255impl HsIdKey {
256 pub fn compute_blinded_key(
258 &self,
259 cur_period: TimePeriod,
260 ) -> Result<(HsBlindIdKey, crate::Subcredential), keymanip::BlindingError> {
261 let secret = b"";
269 let h = self.blinding_factor(secret, cur_period);
270
271 let blinded_key = keymanip::blind_pubkey(&self.0, h)?.into();
272 let subcredential = self.compute_subcredential(&blinded_key, cur_period);
274
275 Ok((blinded_key, subcredential))
276 }
277
278 pub fn compute_subcredential(
280 &self,
281 blinded_key: &HsBlindIdKey,
282 cur_period: TimePeriod,
283 ) -> crate::Subcredential {
284 let subcredential_bytes: [u8; 32] = {
286 let n_hs_cred: [u8; 32] = {
290 let mut h = Sha3_256::new();
291 h.update(b"credential");
292 h.update(self.0.as_bytes());
293 h.finalize().into()
294 };
295 let mut h = Sha3_256::new();
296 h.update(b"subcredential");
297 h.update(n_hs_cred);
298 h.update(blinded_key.as_bytes());
299 h.finalize().into()
300 };
301
302 subcredential_bytes.into()
303 }
304
305 fn blinding_factor(&self, secret: &[u8], cur_period: TimePeriod) -> [u8; 32] {
310 const BLIND_STRING: &[u8] = b"Derive temporary signing key\0";
323 const ED25519_BASEPOINT: &[u8] =
325 b"(15112221349535400772501151409588531511454012693041857206046113283949847762202, \
326 46316835694926478169428394003475163141307993866256225615783033603165251855960)";
327
328 let mut h = Sha3_256::new();
329 h.update(BLIND_STRING);
330 h.update(self.0.as_bytes());
331 h.update(secret);
332 h.update(ED25519_BASEPOINT);
333 h.update(b"key-blind");
334 h.update(cur_period.interval_num.to_be_bytes());
335 h.update((u64::from(cur_period.length.as_minutes())).to_be_bytes());
336
337 h.finalize().into()
338 }
339}
340
341impl HsIdKeypair {
342 pub fn compute_blinded_key(
344 &self,
345 cur_period: TimePeriod,
346 ) -> Result<(HsBlindIdKey, HsBlindIdKeypair, crate::Subcredential), keymanip::BlindingError>
347 {
348 let secret = b"";
352
353 let public_key = HsIdKey(*self.0.public());
354
355 let (blinded_public_key, subcredential) = public_key.compute_blinded_key(cur_period)?;
360
361 let h = public_key.blinding_factor(secret, cur_period);
362
363 let blinded_keypair = keymanip::blind_keypair(&self.0, h)?;
364
365 Ok((blinded_public_key, blinded_keypair.into(), subcredential))
366 }
367}
368
369define_pk_keypair! {
370#[derive(Deftly)]
381#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
382pub struct HsBlindIdKey(ed25519::PublicKey) /
383
384#[derive(Deftly)]
385#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
386HsBlindIdKeypair(ed25519::ExpandedKeypair);
387}
388
389impl From<HsBlindIdKeypair> for HsBlindIdKey {
390 fn from(kp: HsBlindIdKeypair) -> HsBlindIdKey {
391 HsBlindIdKey(kp.0.into())
392 }
393}
394
395define_bytes! {
396#[derive(Copy, Clone, Eq, PartialEq, Hash)]
401pub struct HsBlindId([u8; 32]);
402}
403impl_debug_hex! { HsBlindId .0 }
404
405impl HsBlindIdKey {
406 pub fn id(&self) -> HsBlindId {
410 HsBlindId(self.0.to_bytes().into())
411 }
412}
413impl TryFrom<HsBlindId> for HsBlindIdKey {
414 type Error = signature::Error;
415
416 fn try_from(value: HsBlindId) -> Result<Self, Self::Error> {
417 ed25519::PublicKey::from_bytes(value.0.as_ref()).map(HsBlindIdKey)
418 }
419}
420
421impl From<&HsBlindIdKeypair> for HsBlindIdKey {
422 fn from(value: &HsBlindIdKeypair) -> Self {
423 HsBlindIdKey(*value.0.public())
424 }
425}
426
427impl From<HsBlindIdKey> for HsBlindId {
428 fn from(value: HsBlindIdKey) -> Self {
429 value.id()
430 }
431}
432impl From<ed25519::Ed25519Identity> for HsBlindId {
433 fn from(value: ed25519::Ed25519Identity) -> Self {
434 Self(CtByteArray::from(<[u8; 32]>::from(value)))
435 }
436}
437
438impl Ed25519SigningKey for HsBlindIdKeypair {
439 fn sign(&self, message: &[u8]) -> ed25519::Signature {
440 self.0.sign(message)
441 }
442}
443
444impl Ed25519PublicKey for HsBlindIdKeypair {
445 fn public_key(&self) -> ed25519::PublicKey {
446 *self.0.public()
447 }
448}
449
450define_pk_keypair! {
451#[derive(Deftly)]
465#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
466pub struct HsDescSigningKey(ed25519::PublicKey) /
467
468#[derive(Deftly)]
469#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
470HsDescSigningKeypair(ed25519::Keypair);
471}
472
473define_pk_keypair! {
474#[derive(Deftly)]
482#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
483pub struct HsIntroPtSessionIdKey(ed25519::PublicKey) /
484
485#[derive(Deftly)]
486#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
487HsIntroPtSessionIdKeypair(ed25519::Keypair);
488}
489
490define_pk_keypair! {
491#[derive(Deftly)]
498#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
499pub struct HsSvcNtorKey(curve25519::PublicKey) /
500
501#[derive(Deftly)]
502#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
503HsSvcNtorSecretKey(curve25519::StaticSecret);
504
505#[derive(Deftly)]
506#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
507curve25519_pair as HsSvcNtorKeypair;
508}
509
510mod hs_client_intro_auth {
511 #![allow(deprecated)]
512 use subtle::ConstantTimeEq;
515 use tor_llcrypto::pk::ed25519;
516 use tor_llcrypto::{
517 derive_deftly::Deftly, derive_deftly_template_ConstantTimeEq,
518 derive_deftly_template_PartialEqFromCtEq,
519 };
520
521 use crate::macros::define_pk_keypair;
522
523 define_pk_keypair! {
524 #[deprecated(note = "This key type is not used in the protocol implemented today.")]
530 #[derive(Deftly)]
531 #[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
532 pub struct HsClientIntroAuthKey(ed25519::PublicKey) /
533
534 #[deprecated(note = "This key type is not used in the protocol implemented today.")]
535 #[derive(Deftly)]
536 #[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
537 HsClientIntroAuthKeypair(ed25519::Keypair);
538 }
539}
540
541define_pk_keypair! {
542#[derive(Deftly)]
573#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
574pub struct HsClientDescEncKey(curve25519::PublicKey) /
575
576#[derive(Deftly)]
577#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
578HsClientDescEncSecretKey(curve25519::StaticSecret);
579
580#[derive(Deftly)]
581#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
582curve25519_pair as HsClientDescEncKeypair;
583}
584
585impl Eq for HsClientDescEncKey {}
586
587impl Display for HsClientDescEncKey {
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 let x25519_pk = data_encoding::BASE32_NOPAD.encode(&self.0.to_bytes());
590 write!(f, "descriptor:x25519:{}", x25519_pk)
591 }
592}
593
594impl FromStr for HsClientDescEncKey {
595 type Err = HsClientDescEncKeyParseError;
596
597 fn from_str(key: &str) -> Result<Self, HsClientDescEncKeyParseError> {
598 let (auth_type, key_type, encoded_key) = key
599 .split(':')
600 .collect_tuple()
601 .ok_or(HsClientDescEncKeyParseError::InvalidFormat)?;
602
603 if auth_type != "descriptor" {
604 return Err(HsClientDescEncKeyParseError::InvalidAuthType(
605 auth_type.into(),
606 ));
607 }
608
609 if key_type != "x25519" {
610 return Err(HsClientDescEncKeyParseError::InvalidKeyType(
611 key_type.into(),
612 ));
613 }
614
615 let encoded_key = encoded_key.to_uppercase();
621 let x25519_pk = data_encoding::BASE32_NOPAD.decode(encoded_key.as_bytes())?;
622 let x25519_pk: [u8; 32] = x25519_pk
623 .try_into()
624 .map_err(|_| HsClientDescEncKeyParseError::InvalidKeyMaterial)?;
625
626 Ok(Self(curve25519::PublicKey::from(x25519_pk)))
627 }
628}
629
630#[derive(Error, Clone, Debug, PartialEq)]
632#[non_exhaustive]
633pub enum HsClientDescEncKeyParseError {
634 #[error("Invalid auth type {0}")]
636 InvalidAuthType(String),
637
638 #[error("Invalid key type {0}")]
640 InvalidKeyType(String),
641
642 #[error("Invalid key format")]
644 InvalidFormat,
645
646 #[error("Invalid key material")]
648 InvalidKeyMaterial,
649
650 #[error("Invalid base32 in client key")]
652 InvalidBase32(#[from] data_encoding::DecodeError),
653}
654
655define_pk_keypair! {
656#[derive(Deftly)]
661#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
662pub struct HsSvcDescEncKey(curve25519::PublicKey) /
663
664#[derive(Deftly)]
665#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
666HsSvcDescEncSecretKey(curve25519::StaticSecret);
667}
668
669impl From<&HsClientDescEncSecretKey> for HsClientDescEncKey {
670 fn from(ks: &HsClientDescEncSecretKey) -> Self {
671 Self(curve25519::PublicKey::from(&ks.0))
672 }
673}
674
675impl From<&HsClientDescEncKeypair> for HsClientDescEncKey {
676 fn from(ks: &HsClientDescEncKeypair) -> Self {
677 Self(**ks.public())
678 }
679}
680
681#[allow(clippy::exhaustive_structs)]
684#[derive(Debug, Deftly)]
685#[derive_deftly(ConstantTimeEq, PartialEqFromCtEq)]
686pub struct HsSvcDescEncKeypair {
687 pub public: HsSvcDescEncKey,
689 pub secret: HsSvcDescEncSecretKey,
691}
692
693impl ToEncodableKey for HsClientDescEncKeypair {
700 type Key = curve25519::StaticKeypair;
701 type KeyPair = HsClientDescEncKeypair;
702
703 fn to_encodable_key(self) -> Self::Key {
704 self.into()
705 }
706
707 fn from_encodable_key(key: Self::Key) -> Self {
708 HsClientDescEncKeypair::new(key.public.into(), key.secret.into())
709 }
710}
711
712impl ToEncodableKey for HsBlindIdKeypair {
713 type Key = ed25519::ExpandedKeypair;
714 type KeyPair = HsBlindIdKeypair;
715
716 fn to_encodable_key(self) -> Self::Key {
717 self.into()
718 }
719
720 fn from_encodable_key(key: Self::Key) -> Self {
721 HsBlindIdKeypair::from(key)
722 }
723}
724
725impl ToEncodableKey for HsBlindIdKey {
726 type Key = ed25519::PublicKey;
727 type KeyPair = HsBlindIdKeypair;
728
729 fn to_encodable_key(self) -> Self::Key {
730 self.into()
731 }
732
733 fn from_encodable_key(key: Self::Key) -> Self {
734 HsBlindIdKey::from(key)
735 }
736}
737
738impl ToEncodableKey for HsIdKeypair {
739 type Key = ed25519::ExpandedKeypair;
740 type KeyPair = HsIdKeypair;
741
742 fn to_encodable_key(self) -> Self::Key {
743 self.into()
744 }
745
746 fn from_encodable_key(key: Self::Key) -> Self {
747 HsIdKeypair::from(key)
748 }
749}
750
751impl ToEncodableKey for HsIdKey {
752 type Key = ed25519::PublicKey;
753 type KeyPair = HsIdKeypair;
754
755 fn to_encodable_key(self) -> Self::Key {
756 self.into()
757 }
758
759 fn from_encodable_key(key: Self::Key) -> Self {
760 HsIdKey::from(key)
761 }
762}
763
764impl ToEncodableKey for HsDescSigningKeypair {
765 type Key = ed25519::Keypair;
766 type KeyPair = HsDescSigningKeypair;
767
768 fn to_encodable_key(self) -> Self::Key {
769 self.into()
770 }
771
772 fn from_encodable_key(key: Self::Key) -> Self {
773 HsDescSigningKeypair::from(key)
774 }
775}
776
777impl ToEncodableKey for HsIntroPtSessionIdKeypair {
778 type Key = ed25519::Keypair;
779 type KeyPair = HsIntroPtSessionIdKeypair;
780
781 fn to_encodable_key(self) -> Self::Key {
782 self.into()
783 }
784
785 fn from_encodable_key(key: Self::Key) -> Self {
786 key.into()
787 }
788}
789
790impl ToEncodableKey for HsSvcNtorKeypair {
791 type Key = curve25519::StaticKeypair;
792 type KeyPair = HsSvcNtorKeypair;
793
794 fn to_encodable_key(self) -> Self::Key {
795 self.into()
796 }
797
798 fn from_encodable_key(key: Self::Key) -> Self {
799 key.into()
800 }
801}
802
803#[cfg(test)]
804mod test {
805 #![allow(clippy::bool_assert_comparison)]
807 #![allow(clippy::clone_on_copy)]
808 #![allow(clippy::dbg_macro)]
809 #![allow(clippy::mixed_attributes_style)]
810 #![allow(clippy::print_stderr)]
811 #![allow(clippy::print_stdout)]
812 #![allow(clippy::single_char_pattern)]
813 #![allow(clippy::unwrap_used)]
814 #![allow(clippy::unchecked_duration_subtraction)]
815 #![allow(clippy::useless_vec)]
816 #![allow(clippy::needless_pass_by_value)]
817 use hex_literal::hex;
820 use itertools::izip;
821 use std::time::{Duration, SystemTime};
822 use tor_basic_utils::test_rng::testing_rng;
823
824 use super::*;
825
826 #[test]
827 fn hsid_strings() {
828 use HsIdParseError as PE;
829
830 let hex = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a";
832 let b32 = "25njqamcweflpvkl73j4szahhihoc4xt3ktcgjnpaingr5yhkenl5sid";
833
834 let hsid: [u8; 32] = hex::decode(hex).unwrap().try_into().unwrap();
835 let hsid = HsId::from(hsid);
836 let onion = format!("{}.onion", b32);
837
838 assert_eq!(onion.parse::<HsId>().unwrap(), hsid);
839 assert_eq!(hsid.display_unredacted().to_string(), onion);
840
841 let weird_case: String = izip!(onion.chars(), [false, true].iter().cloned().cycle(),)
842 .map(|(c, swap)| if swap { c.to_ascii_uppercase() } else { c })
843 .collect();
844 dbg!(&weird_case);
845 assert_eq!(weird_case.parse::<HsId>().unwrap(), hsid);
846
847 macro_rules! chk_err { { $s:expr, $($pat:tt)* } => {
848 let e = $s.parse::<HsId>();
849 assert!(matches!(e, Err($($pat)*)), "{:?}", &e);
850 } }
851 let edited = |i, c| {
852 let mut s = b32.to_owned().into_bytes();
853 s[i] = c;
854 format!("{}.onion", String::from_utf8(s).unwrap())
855 };
856
857 chk_err!("wrong", PE::NotOnionDomain);
858 chk_err!("@.onion", PE::InvalidBase32(..));
859 chk_err!("aaaaaaaa.onion", PE::InvalidData(..));
860 chk_err!(edited(55, b'E'), PE::UnsupportedVersion(4));
861 chk_err!(edited(53, b'X'), PE::WrongChecksum);
862 chk_err!(&format!("www.{}", &onion), PE::HsIdContainsSubdomain);
863
864 safelog::with_safe_logging_suppressed(|| {
865 assert_eq!(format!("{:?}", &hsid), format!("HsId({})", onion));
866 });
867
868 assert_eq!(format!("{}", hsid.display_redacted()), "[…]sid.onion");
869 }
870
871 #[test]
872 fn key_blinding_blackbox() {
873 let mut rng = testing_rng();
874 let offset = Duration::new(12 * 60 * 60, 0);
875 let when = TimePeriod::new(Duration::from_secs(3600), SystemTime::now(), offset).unwrap();
876 let keypair = ed25519::Keypair::generate(&mut rng);
877 let id_pub = HsIdKey::from(keypair.verifying_key());
878 let id_keypair = HsIdKeypair::from(ed25519::ExpandedKeypair::from(&keypair));
879
880 let (blinded_pub, subcred1) = id_pub.compute_blinded_key(when).unwrap();
881 let (blinded_pub2, blinded_keypair, subcred2) =
882 id_keypair.compute_blinded_key(when).unwrap();
883
884 assert_eq!(subcred1.as_ref(), subcred2.as_ref());
885 assert_eq!(blinded_pub.0.to_bytes(), blinded_pub2.0.to_bytes());
886 assert_eq!(blinded_pub.id(), blinded_pub2.id());
887
888 let message = b"Here is a terribly important string to authenticate.";
889 let other_message = b"Hey, that is not what I signed!";
890 let sign = blinded_keypair.sign(message);
891
892 assert!(blinded_pub.as_ref().verify(message, &sign).is_ok());
893 assert!(blinded_pub.as_ref().verify(other_message, &sign).is_err());
894 }
895
896 #[test]
897 fn key_blinding_testvec() {
898 let id = HsId::from(hex!(
900 "833990B085C1A688C1D4C8B1F6B56AFAF5A2ECA674449E1D704F83765CCB7BC6"
901 ));
902 let id_pubkey = HsIdKey::try_from(id).unwrap();
903 let id_seckey = HsIdKeypair::from(
904 ed25519::ExpandedKeypair::from_secret_key_bytes(hex!(
905 "D8C7FF0E31295B66540D789AF3E3DF992038A9592EEA01D8B7CBA06D6E66D159
906 4D6167696320576F7264733A20737065697373636F62616C742062697669756D"
907 ))
908 .unwrap(),
909 );
910 let time_period = TimePeriod::new(
911 humantime::parse_duration("1 day").unwrap(),
912 humantime::parse_rfc3339("1973-05-20T01:50:33Z").unwrap(),
913 humantime::parse_duration("12 hours").unwrap(),
914 )
915 .unwrap();
916 assert_eq!(time_period.interval_num, 1234);
917
918 let h = id_pubkey.blinding_factor(b"", time_period);
919 assert_eq!(
920 h,
921 hex!("379E50DB31FEE6775ABD0AF6FB7C371E060308F4F847DB09FE4CFE13AF602287")
922 );
923
924 let (blinded_pub1, subcred1) = id_pubkey.compute_blinded_key(time_period).unwrap();
925 assert_eq!(
926 blinded_pub1.0.to_bytes(),
927 hex!("3A50BF210E8F9EE955AE0014F7A6917FB65EBF098A86305ABB508D1A7291B6D5")
928 );
929 assert_eq!(
930 subcred1.as_ref(),
931 &hex!("635D55907816E8D76398A675A50B1C2F3E36B42A5CA77BA3A0441285161AE07D")
932 );
933
934 let (blinded_pub2, blinded_sec, subcred2) =
935 id_seckey.compute_blinded_key(time_period).unwrap();
936 assert_eq!(blinded_pub1.0.to_bytes(), blinded_pub2.0.to_bytes());
937 assert_eq!(subcred1.as_ref(), subcred2.as_ref());
938 assert_eq!(
939 blinded_sec.0.to_secret_key_bytes(),
940 hex!(
941 "A958DC83AC885F6814C67035DE817A2C604D5D2F715282079448F789B656350B
942 4540FE1F80AA3F7E91306B7BF7A8E367293352B14A29FDCC8C19F3558075524B"
943 )
944 );
945 }
946
947 #[test]
948 fn parse_client_desc_enc_key() {
949 use HsClientDescEncKeyParseError::*;
950
951 const VALID_KEY_BASE32: &str = "dz4q5xqlb4ldnbs72iarrml4ephk3du4i7o2cgiva5lwr6wkquja";
953
954 const WRONG_FORMAT: &[&str] = &["a:b:c:d:e", "descriptor:", "descriptor:x25519", ""];
956
957 for key in WRONG_FORMAT {
958 let err = HsClientDescEncKey::from_str(key).unwrap_err();
959
960 assert_eq!(err, InvalidFormat);
961 }
962
963 let err =
964 HsClientDescEncKey::from_str(&format!("foo:descriptor:x25519:{VALID_KEY_BASE32}"))
965 .unwrap_err();
966
967 assert_eq!(err, InvalidFormat);
968
969 let err = HsClientDescEncKey::from_str("bar:x25519:aa==").unwrap_err();
971 assert_eq!(err, InvalidAuthType("bar".into()));
972
973 let err = HsClientDescEncKey::from_str("descriptor:not-x25519:aa==").unwrap_err();
975 assert_eq!(err, InvalidKeyType("not-x25519".into()));
976
977 let err = HsClientDescEncKey::from_str("descriptor:x25519:aa==").unwrap_err();
979 assert!(matches!(err, InvalidBase32(_)));
980
981 let _key =
983 HsClientDescEncKey::from_str(&format!("descriptor:x25519:{VALID_KEY_BASE32}")).unwrap();
984
985 let desc_enc_key = HsClientDescEncKey::from(curve25519::PublicKey::from(
987 &curve25519::StaticSecret::random_from_rng(testing_rng()),
988 ));
989
990 assert_eq!(
991 desc_enc_key,
992 HsClientDescEncKey::from_str(&desc_enc_key.to_string()).unwrap()
993 );
994 }
995}