deltachat/
key.rs

1//! Cryptographic key module.
2
3use std::collections::BTreeMap;
4use std::fmt;
5use std::io::Cursor;
6
7use anyhow::{Context as _, Result, bail, ensure};
8use base64::Engine as _;
9use deltachat_contact_tools::EmailAddress;
10use pgp::composed::Deserializable;
11pub use pgp::composed::{SignedPublicKey, SignedSecretKey};
12use pgp::ser::Serialize;
13use pgp::types::{KeyDetails, KeyId};
14use tokio::runtime::Handle;
15
16use crate::context::Context;
17use crate::events::EventType;
18use crate::log::LogExt;
19use crate::pgp::KeyPair;
20use crate::tools::{self, time_elapsed};
21
22/// Convenience trait for working with keys.
23///
24/// This trait is implemented for rPGP's [SignedPublicKey] and
25/// [SignedSecretKey] types and makes working with them a little
26/// easier in the deltachat world.
27pub trait DcKey: Serialize + Deserializable + Clone {
28    /// Create a key from some bytes.
29    fn from_slice(bytes: &[u8]) -> Result<Self> {
30        let res = <Self as Deserializable>::from_bytes(Cursor::new(bytes));
31        if let Ok(res) = res {
32            return Ok(res);
33        }
34
35        // Workaround for keys imported using
36        // Delta Chat core < 1.0.0.
37        // Old Delta Chat core had a bug
38        // that resulted in treating CRC24 checksum
39        // as part of the key when reading ASCII Armor.
40        // Some users that started using Delta Chat in 2019
41        // have such corrupted keys with garbage bytes at the end.
42        //
43        // Garbage is at least 3 bytes long
44        // and may be longer due to padding
45        // at the end of the real key data
46        // and importing the key multiple times.
47        //
48        // If removing 10 bytes is not enough,
49        // the key is likely actually corrupted.
50        for garbage_bytes in 3..std::cmp::min(bytes.len(), 10) {
51            let res = <Self as Deserializable>::from_bytes(Cursor::new(
52                bytes
53                    .get(..bytes.len().saturating_sub(garbage_bytes))
54                    .unwrap_or_default(),
55            ));
56            if let Ok(res) = res {
57                return Ok(res);
58            }
59        }
60
61        // Removing garbage bytes did not help, return the error.
62        Ok(res?)
63    }
64
65    /// Create a key from a base64 string.
66    fn from_base64(data: &str) -> Result<Self> {
67        // strip newlines and other whitespace
68        let cleaned: String = data.split_whitespace().collect();
69        let bytes = base64::engine::general_purpose::STANDARD.decode(cleaned.as_bytes())?;
70        Self::from_slice(&bytes)
71    }
72
73    /// Create a key from an ASCII-armored string.
74    fn from_asc(data: &str) -> Result<Self> {
75        let bytes = data.as_bytes();
76        let res = Self::from_armor_single(Cursor::new(bytes));
77        let (key, _headers) = match res {
78            Err(pgp::errors::Error::NoMatchingPacket { .. }) => match Self::is_private() {
79                true => bail!("No private key packet found"),
80                false => bail!("No public key packet found"),
81            },
82            _ => res.context("rPGP error")?,
83        };
84        Ok(key)
85    }
86
87    /// Serialise the key as bytes.
88    fn to_bytes(&self) -> Vec<u8> {
89        // Not using Serialize::to_bytes() to make clear *why* it is
90        // safe to ignore this error.
91        // Because we write to a Vec<u8> the io::Write impls never
92        // fail and we can hide this error.
93        let mut buf = Vec::new();
94        self.to_writer(&mut buf).unwrap();
95        buf
96    }
97
98    /// Serialise the key to a base64 string.
99    fn to_base64(&self) -> String {
100        base64::engine::general_purpose::STANDARD.encode(DcKey::to_bytes(self))
101    }
102
103    /// Serialise the key to ASCII-armored representation.
104    ///
105    /// Each header line must be terminated by `\r\n`.  Only allows setting one
106    /// header as a simplification since that's the only way it's used so far.
107    // Since .to_armored_string() are actual methods on SignedPublicKey and
108    // SignedSecretKey we can not generically implement this.
109    fn to_asc(&self, header: Option<(&str, &str)>) -> String;
110
111    /// The fingerprint for the key.
112    fn dc_fingerprint(&self) -> Fingerprint;
113
114    /// Whether the key is private (or public).
115    fn is_private() -> bool;
116
117    /// Returns the OpenPGP Key ID.
118    fn key_id(&self) -> KeyId;
119}
120
121/// Attempts to load own public key.
122///
123/// Returns `None` if no key is generated yet.
124pub(crate) async fn load_self_public_key_opt(context: &Context) -> Result<Option<SignedPublicKey>> {
125    let Some(public_key_bytes) = context
126        .sql
127        .query_row_optional(
128            "SELECT public_key
129             FROM keypairs
130             WHERE id=(SELECT value FROM config WHERE keyname='key_id')",
131            (),
132            |row| {
133                let bytes: Vec<u8> = row.get(0)?;
134                Ok(bytes)
135            },
136        )
137        .await?
138    else {
139        return Ok(None);
140    };
141    let public_key = SignedPublicKey::from_slice(&public_key_bytes)?;
142    Ok(Some(public_key))
143}
144
145/// Loads own public key.
146///
147/// If no key is generated yet, generates a new one.
148pub(crate) async fn load_self_public_key(context: &Context) -> Result<SignedPublicKey> {
149    match load_self_public_key_opt(context).await? {
150        Some(public_key) => Ok(public_key),
151        None => {
152            let keypair = generate_keypair(context).await?;
153            Ok(keypair.public)
154        }
155    }
156}
157
158/// Returns our own public keyring.
159///
160/// No keys are generated and at most one key is returned.
161pub(crate) async fn load_self_public_keyring(context: &Context) -> Result<Vec<SignedPublicKey>> {
162    if let Some(public_key) = load_self_public_key_opt(context).await? {
163        Ok(vec![public_key])
164    } else {
165        Ok(vec![])
166    }
167}
168
169/// Returns own public key fingerprint in (not human-readable) hex representation.
170/// This is the fingerprint format that is used in the database.
171///
172/// If no key is generated yet, generates a new one.
173///
174/// For performance reasons, the fingerprint is cached after the first invocation.
175pub(crate) async fn self_fingerprint(context: &Context) -> Result<&str> {
176    if let Some(fp) = context.self_fingerprint.get() {
177        Ok(fp)
178    } else {
179        let fp = load_self_public_key(context).await?.dc_fingerprint().hex();
180        Ok(context.self_fingerprint.get_or_init(|| fp))
181    }
182}
183
184/// Returns own public key fingerprint in (not human-readable) hex representation.
185/// This is the fingerprint format that is used in the database.
186///
187/// Returns `None` if no key is generated yet.
188///
189/// For performance reasons, the fingerprint is cached after the first invocation.
190pub(crate) async fn self_fingerprint_opt(context: &Context) -> Result<Option<&str>> {
191    if let Some(fp) = context.self_fingerprint.get() {
192        Ok(Some(fp))
193    } else if let Some(key) = load_self_public_key_opt(context).await? {
194        let fp = key.dc_fingerprint().hex();
195        Ok(Some(context.self_fingerprint.get_or_init(|| fp)))
196    } else {
197        Ok(None)
198    }
199}
200
201pub(crate) async fn load_self_secret_key(context: &Context) -> Result<SignedSecretKey> {
202    let private_key = context
203        .sql
204        .query_row_optional(
205            "SELECT private_key
206             FROM keypairs
207             WHERE id=(SELECT value FROM config WHERE keyname='key_id')",
208            (),
209            |row| {
210                let bytes: Vec<u8> = row.get(0)?;
211                Ok(bytes)
212            },
213        )
214        .await?;
215    match private_key {
216        Some(bytes) => SignedSecretKey::from_slice(&bytes),
217        None => {
218            let keypair = generate_keypair(context).await?;
219            Ok(keypair.secret)
220        }
221    }
222}
223
224pub(crate) async fn load_self_secret_keyring(context: &Context) -> Result<Vec<SignedSecretKey>> {
225    let keys = context
226        .sql
227        .query_map_vec(
228            r#"SELECT private_key
229               FROM keypairs
230               ORDER BY id=(SELECT value FROM config WHERE keyname='key_id') DESC"#,
231            (),
232            |row| {
233                let bytes: Vec<u8> = row.get(0)?;
234                Ok(bytes)
235            },
236        )
237        .await?
238        .into_iter()
239        .filter_map(|bytes| SignedSecretKey::from_slice(&bytes).log_err(context).ok())
240        .collect();
241    Ok(keys)
242}
243
244impl DcKey for SignedPublicKey {
245    fn to_asc(&self, header: Option<(&str, &str)>) -> String {
246        // Not using .to_armored_string() to make clear *why* it is
247        // safe to ignore this error.
248        // Because we write to a Vec<u8> the io::Write impls never
249        // fail and we can hide this error.
250        let headers =
251            header.map(|(key, value)| BTreeMap::from([(key.to_string(), vec![value.to_string()])]));
252        let mut buf = Vec::new();
253        self.to_armored_writer(&mut buf, headers.as_ref().into())
254            .unwrap_or_default();
255        std::string::String::from_utf8(buf).unwrap_or_default()
256    }
257
258    fn is_private() -> bool {
259        false
260    }
261
262    fn dc_fingerprint(&self) -> Fingerprint {
263        self.fingerprint().into()
264    }
265
266    fn key_id(&self) -> KeyId {
267        KeyDetails::legacy_key_id(self)
268    }
269}
270
271impl DcKey for SignedSecretKey {
272    fn to_asc(&self, header: Option<(&str, &str)>) -> String {
273        // Not using .to_armored_string() to make clear *why* it is
274        // safe to do these unwraps.
275        // Because we write to a Vec<u8> the io::Write impls never
276        // fail and we can hide this error.  The string is always ASCII.
277        let headers =
278            header.map(|(key, value)| BTreeMap::from([(key.to_string(), vec![value.to_string()])]));
279        let mut buf = Vec::new();
280        self.to_armored_writer(&mut buf, headers.as_ref().into())
281            .unwrap_or_default();
282        std::string::String::from_utf8(buf).unwrap_or_default()
283    }
284
285    fn is_private() -> bool {
286        true
287    }
288
289    fn dc_fingerprint(&self) -> Fingerprint {
290        self.fingerprint().into()
291    }
292
293    fn key_id(&self) -> KeyId {
294        KeyDetails::legacy_key_id(&**self)
295    }
296}
297
298async fn generate_keypair(context: &Context) -> Result<KeyPair> {
299    let addr = context.get_primary_self_addr().await?;
300    let addr = EmailAddress::new(&addr)?;
301    let _guard = context.generating_key_mutex.lock().await;
302
303    // Check if the key appeared while we were waiting on the lock.
304    match load_keypair(context).await? {
305        Some(key_pair) => Ok(key_pair),
306        None => {
307            let start = tools::Time::now();
308            info!(context, "Generating keypair.");
309            let keypair = Handle::current()
310                .spawn_blocking(move || crate::pgp::create_keypair(addr))
311                .await??;
312
313            store_self_keypair(context, &keypair).await?;
314            info!(
315                context,
316                "Keypair generated in {:.3}s.",
317                time_elapsed(&start).as_secs(),
318            );
319            Ok(keypair)
320        }
321    }
322}
323
324pub(crate) async fn load_keypair(context: &Context) -> Result<Option<KeyPair>> {
325    let res = context
326        .sql
327        .query_row_optional(
328            "SELECT public_key, private_key
329             FROM keypairs
330             WHERE id=(SELECT value FROM config WHERE keyname='key_id')",
331            (),
332            |row| {
333                let pub_bytes: Vec<u8> = row.get(0)?;
334                let sec_bytes: Vec<u8> = row.get(1)?;
335                Ok((pub_bytes, sec_bytes))
336            },
337        )
338        .await?;
339
340    Ok(if let Some((pub_bytes, sec_bytes)) = res {
341        Some(KeyPair {
342            public: SignedPublicKey::from_slice(&pub_bytes)?,
343            secret: SignedSecretKey::from_slice(&sec_bytes)?,
344        })
345    } else {
346        None
347    })
348}
349
350/// Store the keypair as an owned keypair for addr in the database.
351///
352/// This will save the keypair as keys for the given address.  The
353/// "self" here refers to the fact that this DC instance owns the
354/// keypair.  Usually `addr` will be [Config::ConfiguredAddr].
355///
356/// If either the public or private keys are already present in the
357/// database, this entry will be removed first regardless of the
358/// address associated with it.  Practically this means saving the
359/// same key again overwrites it.
360///
361/// [Config::ConfiguredAddr]: crate::config::Config::ConfiguredAddr
362pub(crate) async fn store_self_keypair(context: &Context, keypair: &KeyPair) -> Result<()> {
363    let mut config_cache_lock = context.sql.config_cache.write().await;
364    let new_key_id = context
365        .sql
366        .transaction(|transaction| {
367            let public_key = DcKey::to_bytes(&keypair.public);
368            let secret_key = DcKey::to_bytes(&keypair.secret);
369
370            // private_key and public_key columns
371            // are UNIQUE since migration 107,
372            // so this fails if we already have this key.
373            transaction
374                .execute(
375                    "INSERT INTO keypairs (public_key, private_key)
376                     VALUES (?,?)",
377                    (&public_key, &secret_key),
378                )
379                .context("Failed to insert keypair")?;
380
381            let new_key_id = transaction.last_insert_rowid();
382
383            // This will fail if we already have `key_id`.
384            //
385            // Setting default key is only possible if we don't
386            // have a key already.
387            transaction.execute(
388                "INSERT INTO config (keyname, value) VALUES ('key_id', ?)",
389                (new_key_id,),
390            )?;
391            Ok(new_key_id)
392        })
393        .await?;
394    context.emit_event(EventType::AccountsItemChanged);
395    config_cache_lock.insert("key_id".to_string(), Some(new_key_id.to_string()));
396    Ok(())
397}
398
399/// Saves a keypair as the default keys.
400///
401/// This API is used for testing purposes
402/// to avoid generating the key in tests.
403/// Use import/export APIs instead.
404pub async fn preconfigure_keypair(context: &Context, secret_data: &str) -> Result<()> {
405    let secret = SignedSecretKey::from_asc(secret_data)?;
406    let public = secret.to_public_key();
407    let keypair = KeyPair { public, secret };
408    store_self_keypair(context, &keypair).await?;
409    Ok(())
410}
411
412/// A key fingerprint
413#[derive(Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
414pub struct Fingerprint(Vec<u8>);
415
416impl Fingerprint {
417    /// Creates new 160-bit (20 bytes) fingerprint.
418    pub fn new(v: Vec<u8>) -> Fingerprint {
419        debug_assert_eq!(v.len(), 20);
420        Fingerprint(v)
421    }
422
423    /// Make a hex string from the fingerprint.
424    ///
425    /// Use [std::fmt::Display] or [ToString::to_string] to get a
426    /// human-readable formatted string.
427    pub fn hex(&self) -> String {
428        hex::encode_upper(&self.0)
429    }
430}
431
432impl From<pgp::types::Fingerprint> for Fingerprint {
433    fn from(fingerprint: pgp::types::Fingerprint) -> Fingerprint {
434        Self::new(fingerprint.as_bytes().into())
435    }
436}
437
438impl fmt::Debug for Fingerprint {
439    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
440        f.debug_struct("Fingerprint")
441            .field("hex", &self.hex())
442            .finish()
443    }
444}
445
446/// Make a human-readable fingerprint.
447impl fmt::Display for Fingerprint {
448    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449        // Split key into chunks of 4 with space and newline at 20 chars
450        for (i, c) in self.hex().chars().enumerate() {
451            if i > 0 && i % 20 == 0 {
452                writeln!(f)?;
453            } else if i > 0 && i % 4 == 0 {
454                write!(f, " ")?;
455            }
456            write!(f, "{c}")?;
457        }
458        Ok(())
459    }
460}
461
462/// Parse a human-readable or otherwise formatted fingerprint.
463impl std::str::FromStr for Fingerprint {
464    type Err = anyhow::Error;
465
466    fn from_str(input: &str) -> Result<Self> {
467        let hex_repr: String = input
468            .to_uppercase()
469            .chars()
470            .filter(|&c| c.is_ascii_hexdigit())
471            .collect();
472        let v: Vec<u8> = hex::decode(&hex_repr)?;
473        ensure!(v.len() == 20, "wrong fingerprint length: {hex_repr}");
474        let fp = Fingerprint::new(v);
475        Ok(fp)
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use std::sync::{Arc, LazyLock};
482
483    use super::*;
484    use crate::config::Config;
485    use crate::test_utils::{TestContext, alice_keypair};
486
487    static KEYPAIR: LazyLock<KeyPair> = LazyLock::new(alice_keypair);
488
489    #[test]
490    fn test_from_armored_string() {
491        let private_key = SignedSecretKey::from_asc(
492            "-----BEGIN PGP PRIVATE KEY BLOCK-----
493
494xcLYBF0fgz4BCADnRUV52V4xhSsU56ZaAn3+3oG86MZhXy4X8w14WZZDf0VJGeTh
495oTtVwi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TEf
544V2Fclh+G0sWp7F2ZS3nt0vX1hYG8TMIzM8Bj2eMsdXATOji9ST7EUxk/BpFax86D
545i8pcjGO+IZffvyZJVRWfVooBJmWWbPB1pueo3tx8w3+fcuzpxz+RLFKaPyqXO+dD
5467yPJeQ==
547=KZk/
548-----END PGP PRIVATE KEY BLOCK-----",
549        )
550        .expect("failed to decode");
551        let binary = DcKey::to_bytes(&private_key);
552        SignedSecretKey::from_slice(&binary).expect("invalid private key");
553    }
554
555    #[test]
556    fn test_asc_roundtrip() {
557        let key = KEYPAIR.public.clone();
558        let asc = key.to_asc(Some(("spam", "ham")));
559        let key2 = SignedPublicKey::from_asc(&asc).unwrap();
560        assert_eq!(key, key2);
561
562        let key = KEYPAIR.secret.clone();
563        let asc = key.to_asc(Some(("spam", "ham")));
564        let key2 = SignedSecretKey::from_asc(&asc).unwrap();
565        assert_eq!(key, key2);
566    }
567
568    #[test]
569    fn test_from_slice_roundtrip() {
570        let public_key = KEYPAIR.public.clone();
571        let private_key = KEYPAIR.secret.clone();
572
573        let binary = DcKey::to_bytes(&public_key);
574        let public_key2 = SignedPublicKey::from_slice(&binary).expect("invalid public key");
575        assert_eq!(public_key, public_key2);
576
577        let binary = DcKey::to_bytes(&private_key);
578        let private_key2 = SignedSecretKey::from_slice(&binary).expect("invalid private key");
579        assert_eq!(private_key, private_key2);
580    }
581
582    #[test]
583    fn test_from_slice_bad_data() {
584        let mut bad_data: [u8; 4096] = [0; 4096];
585        for (i, v) in bad_data.iter_mut().enumerate() {
586            *v = (i & 0xff) as u8;
587        }
588        for j in 0..(4096 / 40) {
589            let slice = &bad_data.get(j..j + 4096 / 2 + j).unwrap();
590            assert!(SignedPublicKey::from_slice(slice).is_err());
591            assert!(SignedSecretKey::from_slice(slice).is_err());
592        }
593    }
594
595    /// Tests workaround for Delta Chat core < 1.0.0
596    /// which parsed CRC24 at the end of ASCII Armor
597    /// as the part of the key.
598    /// Depending on the alignment and the number of
599    /// `=` characters at the end of the key,
600    /// this resulted in various number of garbage
601    /// octets at the end of the key, starting from 3 octets,
602    /// but possibly 4 or 5 and maybe more octets
603    /// if the key is imported or transferred
604    /// using Autocrypt Setup Message multiple times.
605    #[test]
606    fn test_ignore_trailing_garbage() {
607        // Test several variants of garbage.
608        for garbage in [
609            b"\x02\xfc\xaa\x38\x4b\x5c".as_slice(),
610            b"\x02\xfc\xaa".as_slice(),
611            b"\x01\x02\x03\x04\x05".as_slice(),
612        ] {
613            let private_key = KEYPAIR.secret.clone();
614
615            let mut binary = DcKey::to_bytes(&private_key);
616            binary.extend(garbage);
617
618            let private_key2 =
619                SignedSecretKey::from_slice(&binary).expect("Failed to ignore garbage");
620
621            assert_eq!(private_key.dc_fingerprint(), private_key2.dc_fingerprint());
622        }
623    }
624
625    #[test]
626    fn test_base64_roundtrip() {
627        let key = KEYPAIR.public.clone();
628        let base64 = key.to_base64();
629        let key2 = SignedPublicKey::from_base64(&base64).unwrap();
630        assert_eq!(key, key2);
631    }
632
633    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
634    async fn test_load_self_generate_public() {
635        let t = TestContext::new().await;
636        t.set_config(Config::ConfiguredAddr, Some("alice@example.org"))
637            .await
638            .unwrap();
639        let key = load_self_public_key(&t).await;
640        assert!(key.is_ok());
641    }
642
643    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
644    async fn test_load_self_generate_secret() {
645        let t = TestContext::new().await;
646        t.set_config(Config::ConfiguredAddr, Some("alice@example.org"))
647            .await
648            .unwrap();
649        let key = load_self_secret_key(&t).await;
650        assert!(key.is_ok());
651    }
652
653    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
654    async fn test_load_self_generate_concurrent() {
655        use std::thread;
656
657        let t = TestContext::new().await;
658        t.set_config(Config::ConfiguredAddr, Some("alice@example.org"))
659            .await
660            .unwrap();
661        let thr0 = {
662            let ctx = t.clone();
663            thread::spawn(move || {
664                tokio::runtime::Runtime::new()
665                    .unwrap()
666                    .block_on(load_self_public_key(&ctx))
667            })
668        };
669        let thr1 = {
670            let ctx = t.clone();
671            thread::spawn(move || {
672                tokio::runtime::Runtime::new()
673                    .unwrap()
674                    .block_on(load_self_public_key(&ctx))
675            })
676        };
677        let res0 = thr0.join().unwrap();
678        let res1 = thr1.join().unwrap();
679        assert_eq!(res0.unwrap(), res1.unwrap());
680    }
681
682    /// Tests that setting a default key second time is not allowed.
683    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
684    async fn test_save_self_key_twice() {
685        // Saving the same key twice should result in only one row in
686        // the keypairs table.
687        let t = TestContext::new().await;
688        let ctx = Arc::new(t);
689
690        let nrows = || async {
691            ctx.sql
692                .count("SELECT COUNT(*) FROM keypairs;", ())
693                .await
694                .unwrap()
695        };
696        assert_eq!(nrows().await, 0);
697        store_self_keypair(&ctx, &KEYPAIR).await.unwrap();
698        assert_eq!(nrows().await, 1);
699
700        // Saving a second key fails.
701        let res = store_self_keypair(&ctx, &KEYPAIR).await;
702        assert!(res.is_err());
703
704        assert_eq!(nrows().await, 1);
705    }
706
707    #[test]
708    fn test_fingerprint_from_str() {
709        let res = Fingerprint::new(vec![
710            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
711        ]);
712
713        let fp: Fingerprint = "0102030405060708090A0B0c0d0e0F1011121314".parse().unwrap();
714        assert_eq!(fp, res);
715
716        let fp: Fingerprint = "zzzz 0102 0304 0506\n0708090a0b0c0D0E0F1011121314 yyy"
717            .parse()
718            .unwrap();
719        assert_eq!(fp, res);
720
721        assert!("1".parse::<Fingerprint>().is_err());
722    }
723
724    #[test]
725    fn test_fingerprint_hex() {
726        let fp = Fingerprint::new(vec![
727            1, 2, 4, 8, 16, 32, 64, 128, 255, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
728        ]);
729        assert_eq!(fp.hex(), "0102040810204080FF0A0B0C0D0E0F1011121314");
730    }
731
732    #[test]
733    fn test_fingerprint_to_string() {
734        let fp = Fingerprint::new(vec![
735            1, 2, 4, 8, 16, 32, 64, 128, 255, 1, 2, 4, 8, 16, 32, 64, 128, 255, 19, 20,
736        ]);
737        assert_eq!(
738            fp.to_string(),
739            "0102 0408 1020 4080 FF01\n0204 0810 2040 80FF 1314"
740        );
741    }
742}