stegtext 0.1.0

Text steganography command-line tool and library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Text [steganography][] tool.
//!
//! Hide secret value in [UTF-8][] text using [homoglyphs][].
//!
//! See also: [IDN homograph attack][].
//!
//! # Examples
//!
//! Hide secret in text:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // secret
//! const SECRET: [u8; 5] = *b"hello";
//!
//! // input text
//! const TEXT: &str = "\
//! Тhe Нitсhhikеr's Guіdе to thе Galaxy is a 1979 ѕcіеncе fiсtion соmedy
//! novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
//! of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
//!
//! // expected output
//! const EXP: &str = "\
//! Тhe Нitсhhikеr's Guide to the Galaxy is a 1979 ѕcіеncе fiсtion соmedy
//! novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
//! of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
//!
//! // encode secret, check result
//! assert_eq!(stegtext::encode(&SECRET, TEXT)?, EXP);
//! # Ok(())
//! # }
//! ```
//!
//! Get secret from text:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // text with embedded secret
//! const TEXT: &str = "\
//! Тhe Нitсhhikеr's Guide to the Galaxy is a 1979 ѕcіеncе fiсtion соmedy
//! novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
//! of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
//!
//! // decode secret, check result
//! assert_eq!(stegtext::decode(TEXT)?, "hello");
//! # Ok(())
//! # }
//! ```
//!
//! Get text embedding capacity:
//!
//! ```
//! # fn main() {
//! // input text
//! const TEXT: &str = "\
//! Тhe Нitсhhikеr's Guіdе to thе Galaxy is a 1979 ѕcіеncе fiсtion соmedy
//! novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
//! of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name. Іt centrеѕ оn the
//! misаdvеntureѕ оf Arthur Dent, the оnly man tо ѕurvive the destruction of
//! Earth, as he roams the cosmos and learns the truth behind his very
//! existence. The novel's namesake is an in-universe electronic travel
//! guide written in the form of an encyclopaedia, through which the story
//! is framed.";
//!
//! // calculate capacity, check result
//! assert_eq!(stegtext::capacity(TEXT), 23);
//! # }
//! ```
//!
//! # Technical Details
//!
//! Encoding process:
//!
//! 1. The first prefix byte is constructed.  The lower 4 bits of the
//!    first prefix byte are the are a constant tag (`0x5`) and the
//!    upper 4 bits of the first prefix byte are bits `0..4` of the
//!    length of the secret.
//! 2. The second prefix byte is constructed from bits `4..12` of the
//!    length of the secret.
//! 3. The secret bytes are appended to the prefix bytes to create a
//!    payload.
//! 4. The total number of payload bits are calculated.
//! 5. The input text is scanned for characters that can be replaced
//!    by [homoglyphs][].
//! 6. Non-matching characters are passed through to the output
//!    unaltered.
//! 7. When a matching character is encountered it is modified
//!    based on the value of the current payload bit:
//!    - if the current payload bit is **set**, then the character
//!      is replaced with a non-Latin [homoglyph][] character.  For
//!      example, [`'A'` (`U+0041`)][a-l] is replaced with [`'А'` (`U+0410`)][a-c],
//!      [`'B'` (`U+0042`)][b-l] is replaced by [`'В'` (`U+0412`)][b-c],
//!      and so on.
//!    - if the current payload bit is **not set**, then the character
//!      is replaced with a Latin character.
//! 8. The current payload bit position is incremented.
//! 9. Steps 5-8 are repeated until the current payload bit position
//!    equals the total number of payload bits.
//! 10. If payload bits remain when the end of the input text is
//!     reached, then [`Err::Capacity`] is returned.
//! 11. Once all the payload bits have been encoded, the remaining
//!     characters from the input text are passed through to the output
//!     unaltered.
//!
//! [steganography]: https://en.wikipedia.org/wiki/Steganography
//!   "Steganography (Wikipedia)"
//! [utf-8]: https://en.wikipedia.org/wiki/UTF-8
//!   "UTF-8 (Wikipedia)"
//! [homoglyph]: https://en.wikipedia.org/wiki/Homoglyph
//!   "Homoglyph (Wikipedia)"
//! [homoglyphs]: https://en.wikipedia.org/wiki/Homoglyph
//!   "Homoglyph (Wikipedia)"
//! [idn homograph attack]: https://en.wikipedia.org/wiki/IDN_homograph_attack#Cyrillic
//!   "IDN homograph attack (Wikipedia)"
//! [a-l]: https://en.wikipedia.org/wiki/A
//!   "A (Latin)"
//! [a-c]: https://en.wikipedia.org/wiki/A_(Cyrillic)
//!   "A (Cyrillic)"
//! [b-l]: https://en.wikipedia.org/wiki/B
//!   "B (Latin)"
//! [b-c]: https://en.wikipedia.org/wiki/B_(Cyrillic)
//!   "B (Cyrillic)"

#![deny(missing_docs)]
#![deny(unsafe_code)]

use std::io::Write;

/// Prefix tag.
///
/// Lower 4 bits of first decoded byte.  Used to identify text with
/// embedded steganographic data.
const TAG: u8 = 0x5;

/// Maximum secret length.
///
/// Note: encoded in prefix bytes as a 12-bit integer.
const MAX_SECRET_LEN: usize = 4095;

/// Encode/decode error.
#[derive(Debug, PartialEq)]
pub enum Err {
  /// Secret length is greater than 4095 bytes.
  SecretLen(usize),

  /// Not enough text capacity to encode secret.
  Capacity,

  /// Write to output buffer failed.
  Write,

  /// UTF-8 encoding error.
  Encoding(std::string::FromUtf8Error),

  /// Invalid tag in encoded text.
  BadTag(u8),

  /// Truncated secret.
  TruncatedSecret(usize, usize),
}

impl std::error::Error for Err {}

impl std::fmt::Display for Err {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      Err::SecretLen(len) => write!(f, "secret length greater than {MAX_SECRET_LEN} bytes: {len}"),
      Err::Capacity => write!(f, "not enough text capacity to encode secret"),
      Err::Write => write!(f, "buffer write failed"),
      Err::Encoding(err) => write!(f, "encode error: {err}"),
      Err::BadTag(val) => write!(f, "invalid tag: got 0x{val:x}, expected 0x{TAG:x}"),
      Err::TruncatedSecret(got, exp) => write!(f, "truncated secret: got {got} bytes, expected {exp} bytes"),
    }
  }
}

/// Does this character have a homoglyph?
fn is_encodable(c: char) -> bool {
  matches!(c, 'A' | 'B' | 'C' | 'E' | 'H' | 'I' | 'J' | 'K' | 'M' | 'O' | 'P' | 'S' | 'T' | 'X' | 'a' | 'c' | 'e' | 'i' | 'j' | 'o' | 'p' | 'q' | 's' | 'w' | 'x' | 'y' | 'А' | 'В' | 'С' | 'Е' | 'Н' | 'І' | 'Ј' | 'К' | 'М' | 'О' | 'Р' | 'Ѕ' | 'Т' | 'Х' | 'а' | 'с' | 'е' | 'і' | 'ј' | 'о' | 'р' | 'ԛ' | 'ѕ' | 'ԝ' | 'х' | 'у')
}

/// Encode bit value in character.
fn encode_char(c: char, bit: bool) -> char {
  match (c, bit) {
    ('A' | 'А', true) => 'А',
    ('A' | 'А', false) => 'A',
    ('B' | 'В', true) => 'В',
    ('B' | 'В', false) => 'B',
    ('C' | 'С', true) => 'С',
    ('C' | 'С', false) => 'C',
    ('E' | 'Е', true) => 'Е',
    ('E' | 'Е', false) => 'E',
    ('H' | 'Н', true) => 'Н',
    ('H' | 'Н', false) => 'H',
    ('I' | 'І', true) => 'І',
    ('I' | 'І', false) => 'I',
    ('J' | 'Ј', true) => 'Ј',
    ('J' | 'Ј', false) => 'J',
    ('K' | 'К', true) => 'К',
    ('K' | 'К', false) => 'K',
    ('M' | 'М', true) => 'М',
    ('M' | 'М', false) => 'M',
    ('O' | 'О', true) => 'О',
    ('O' | 'О', false) => 'O',
    ('P' | 'Р', true) => 'Р',
    ('P' | 'Р', false) => 'P',
    ('S' | 'Ѕ', true) => 'Ѕ',
    ('S' | 'Ѕ', false) => 'S',
    ('T' | 'Т', true) => 'Т',
    ('T' | 'Т', false) => 'T',
    ('X' | 'Х', true) => 'Х',
    ('X' | 'Х', false) => 'X',
    ('a' | 'а', true) => 'а',
    ('a' | 'а', false) => 'a',
    ('c' | 'с', true) => 'с',
    ('c' | 'с', false) => 'c',
    ('e' | 'е', true) => 'е',
    ('e' | 'е', false) => 'e',
    ('i' | 'і', true) => 'і',
    ('i' | 'і', false) => 'i',
    ('j' | 'ј', true) => 'ј',
    ('j' | 'ј', false) => 'j',
    ('o' | 'о', true) => 'о',
    ('o' | 'о', false) => 'o',
    ('p' | 'р', true) => 'р',
    ('p' | 'р', false) => 'p',
    ('q' | 'ԛ', true) => 'ԛ',
    ('q' | 'ԛ', false) => 'q',
    ('s' | 'ѕ', true) => 'ѕ',
    ('s' | 'ѕ', false) => 's',
    ('w' | 'ԝ', true) => 'ԝ',
    ('w' | 'ԝ', false) => 'w',
    ('x' | 'х', true) => 'х',
    ('x' | 'х', false) => 'x',
    ('y' | 'у', true) => 'у',
    ('y' | 'у', false) => 'y',
    _ => c,
  }
}

/// Hide secret in text and return result as byte vector.
pub fn encode_vec(secret: &[u8], text: &str) -> Result<Vec<u8>, Err> {
  // check secret length
  if secret.len() > MAX_SECRET_LEN {
    return Err(Err::SecretLen(secret.len()));
  }

  // build tag byte and encoded secret
  let tag_byte = (((secret.len() & 0xf) << 4) as u8) | TAG;
  let mut src = vec![tag_byte, (secret.len() >> 4) as u8];
  src.extend(secret);

  let mut src_pos: usize = 0; // bit position
  let src_bit_len = src.len() << 3; // src len, in bits

  // build output
  let mut dst = Vec::new();
  for c in text.chars() {
    let c = if src_pos < src_bit_len && is_encodable(c) {
      let bit = ((src[src_pos >> 3] >> (src_pos & 7)) & 1) == 1;
      src_pos += 1;
      encode_char(c, bit)
    } else {
      c // pass character through
    };

    // write character to output buffer
    match write!(dst, "{c}") {
      Ok(_) => {},
      Err(_) => return Err(Err::Write),
    }
  }

  // were all secret bits encoded?
  if src_pos != src_bit_len {
    return Err(Err::Capacity)
  }

  Ok(dst)
}

/// Hide secret in text and return result as string.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // secret
/// const SECRET: [u8; 5] = *b"hello";
///
/// // input text
/// const TEXT: &str = "\
/// Тhe Нitсhhikеr's Guіdе to thе Galaxy is a 1979 ѕcіеncе fiсtion соmedy
/// novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
/// of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
///
/// // expected output
/// const EXP: &str = "\
/// Тhe Нitсhhikеr's Guide to the Galaxy is a 1979 ѕcіеncе fiсtion соmedy
/// novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
/// of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
///
/// // encode secret, check result
/// assert_eq!(stegtext::encode(&SECRET, TEXT)?, EXP);
/// # Ok(())
/// # }
/// ```
pub fn encode(secret: &[u8], text: &str) -> Result<String, Err> {
  match encode_vec(secret, text) {
    Ok(vec) => match String::from_utf8(vec) {
      Ok(s) => Ok(s),
      Err(err) => Err(Err::Encoding(err)),
    }
    Err(err) => Err(err),
  }
}

/// Get embedding capacity, in bytes.
///
/// # Example
///
/// ```
/// # fn main() {
/// // input text
/// const TEXT: &str = "\
/// Тhe Нitсhhikеr's Guіdе to thе Galaxy is a 1979 ѕcіеncе fiсtion соmedy
/// novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
/// of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name. Іt centrеѕ оn the
/// misаdvеntureѕ оf Arthur Dent, the оnly man tо ѕurvive the destruction of
/// Earth, as he roams the cosmos and learns the truth behind his very
/// existence. The novel's namesake is an in-universe electronic travel
/// guide written in the form of an encyclopaedia, through which the story
/// is framed.";
///
/// // get capacity, check result
/// assert_eq!(stegtext::capacity(TEXT), 23);
/// # }
/// ```
pub fn capacity(text: &str) -> usize {
  if let len = text.chars().filter(|c| is_encodable(*c)).count() && len > 16 {
    // truncate to multiple of 8, subtract two bytes for tag and length
    (len / 8) - 2
  } else {
    0
  }
}

/// Maybe decode bit from character.
fn decode_char(c: char) -> Option<bool> {
  match c {
    'A' | 'B' | 'C' | 'E' | 'H' | 'I' | 'J' | 'K' | 'M' | 'O' | 'P' | 'S' | 'T' | 'X' | 'a' | 'c' | 'e' | 'i' | 'j' | 'o' | 'p' | 'q' | 's' | 'w' | 'x' | 'y' => Some(false), // latin
    'А' | 'В' | 'С' | 'Е' | 'Н' | 'І' | 'Ј' | 'К' | 'М' | 'О' | 'Р' | 'Ѕ' | 'Т' | 'Х' | 'а' | 'с' | 'е' | 'і' | 'ј' | 'о' | 'р' | 'ԛ' | 'ѕ' | 'ԝ' | 'х' | 'у' => Some(true), // cyrillic
    _ => None,
  }
}

/// Extract secret from text and return result as byte vector.
pub fn decode_vec(text: &str) -> Result<Vec<u8>, Err> {
  let mut pos: usize = 0; // current bit
  let mut byte: u8 = 0; // current byte
  let mut exp_len: usize = 0; // expected output length

  let mut dst = Vec::new(); // output vector
  for c in text.chars() {
    if let Some(bit) = decode_char(c) {
      byte |= u8::from(bit) << pos;
      pos += 1; // advance

      if pos == 8 {
        dst.push(byte); // add byte to output
        byte = 0; // clear byte
        pos = 0; // clear position

        match (exp_len, dst.len()) {
          (0, 2) => {
            // get tag and expected length
            let tag = dst[0] & 0xf;
            exp_len = ((dst[0] >> 4) as usize) | ((dst[1] as usize) << 8);

            // check tag and length
            if tag != TAG {
              return Err(Err::BadTag(tag));
            } else if exp_len == 0 {
              return Ok(dst);
            }

            dst.clear(); // clear vector
          },
          (_, dst_len) if dst_len == exp_len => break,
          (_, _) => {},
        };
      }
    }
  }

  // check decoded secret length
  if dst.len() == exp_len {
    Ok(dst)
  } else {
    Err(Err::TruncatedSecret(dst.len(), exp_len))
  }
}

/// Extract secret from text and return result as string.
///
/// ```
/// // Text with hidden secret.
/// const TEXT: &str = "\
/// Тhe Нitсhhikеr's Guide to the Galaxy is a 1979 ѕcіеncе fiсtion соmedy
/// novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
/// of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // decode secret, check result
/// assert_eq!(stegtext::decode(TEXT)?, "hello");
/// # Ok(())
/// # }
/// ```
pub fn decode(text: &str) -> Result<String, Err> {
  match decode_vec(text) {
    Ok(vec) => match String::from_utf8(vec) {
      Ok(s) => Ok(s),
      Err(err) => Err(Err::Encoding(err)),
    },
    Err(err) => Err(err),
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_encode_vec_fail() {
    let tests = vec![(
      "long secret", // name
      [0u8; MAX_SECRET_LEN+1].to_vec(), // secret
      "aaaaaaaa aaaaaaaa aaaaaaaa", // text
      Err(Err::SecretLen(MAX_SECRET_LEN+1)),
    ), (
      "short text", // name
      vec![0u8], // secret
      "aaaaaaaa aaaaaaaa", // text
      Err(Err::Capacity),
    )];

    for (name, msg, text, exp) in tests {
      assert_eq!(encode_vec(&msg, text), exp, "{name}");
    }
  }

  #[test]
  fn test_encode_vec_pass() {
    let tests = vec![(
      "aaa", // name
      vec![1], // secret
      "aaaaaaaa aaaaaaaa aaaaaaaa", // text
      vec![ // exp
        0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0x61, 0x61,
        0x20,
        0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
        0x20,
        0xd0, 0xb0, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
      ],
    ), (
      "acc", // name
      vec![1], // secret
      "aaaaaaaa cccccccc cccccccc", // text
      vec![ // exp
        0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0x61, 0x61,
        0x20,
        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
        0x20,
        0xd1, 0x81, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
      ],
    ), (
      "ace", // name
      vec![1], // secret
      "aaaaaaaa cccccccc eeeeeeee", // text
      vec![ // exp
        0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0x61, 0x61,
        0x20,
        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
        0x20,
        0xd0, 0xb5, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
      ],
    ), (
      "aop", // name
      vec![1], // secret
      "aaaaaaaa oooooooo pppppppp", // text
      vec![ // exp
        0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0x61, 0x61,
        0x20,
        0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f,
        0x20,
        0xd1, 0x80, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70,
      ],
    ), (
      "pxy", // name
      vec![1], // secret
      "pppppppp xxxxxxxx yyyyyyyy", // text
      vec![ // exp
        0xd1, 0x80, 0x70, 0xd1, 0x80, 0x70, 0xd1, 0x80, 0x70, 0x70, 0x70,
        0x20,
        0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78,
        0x20,
        0xd1, 0x83, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79,
      ],
    ), (
      "ijqs", // name
      vec![1, 1], // secret
      "iiiiiiii jjjjjjjj qqqqqqqq ssssssss", // text
      vec![ // exp
        0xd1, 0x96, 0x69, 0xd1, 0x96, 0x69, 0x69, 0xd1, 0x96, 0x69, 0x69,
        0x20,
        0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a,
        0x20,
        0xd4, 0x9b, 0x71, 0x71, 0x71, 0x71, 0x71, 0x71, 0x71,
        0x20,
        0xd1, 0x95, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73,
      ],
    ), (
      "wwww", // name
      vec![1, 1], // secret
      "wwwwwwww wwwwwwww wwwwwwww wwwwwwww", // text
      vec![ // exp
        0xd4, 0x9d, 0x77, 0xd4, 0x9d, 0x77, 0x77, 0xd4, 0x9d, 0x77, 0x77,
        0x20,
        0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
        0x20,
        0xd4, 0x9d, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
        0x20,
        0xd4, 0x9d, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
      ],
    ), (
      "ABCE", // name
      vec![1, 1], // secret
      "AAAAAAAA BBBBBBBB CCCCCCCC EEEEEEEE", // text
      vec![ // exp
        0xd0, 0x90, 0x41, 0xd0, 0x90, 0x41, 0x41, 0xd0, 0x90, 0x41, 0x41,
        0x20,
        0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42,
        0x20,
        0xd0, 0xa1, 0x43, 0x43, 0x43, 0x43, 0x43, 0x43, 0x43,
        0x20,
        0xd0, 0x95, 0x45, 0x45, 0x45, 0x45, 0x45, 0x45, 0x45,
      ],
    ), (
      "HIJKM", // name
      vec![1, 1, 1], // secret
      "HHHHHHHH IIIIIIII JJJJJJJJ KKKKKKKK MMMMMMMM", // text
      vec![ // exp
        0xd0, 0x9d, 0x48, 0xd0, 0x9d, 0x48, 0xd0, 0x9d, 0xd0, 0x9d, 0x48, 0x48,
        0x20,
        0x49, 0x49, 0x49, 0x49, 0x49, 0x49, 0x49, 0x49,
        0x20,
        0xd0, 0x88, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a,
        0x20,
        0xd0, 0x9a, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b,
        0x20,
        0xd0, 0x9c, 0x4d, 0x4d, 0x4d, 0x4d, 0x4d, 0x4d, 0x4d,
      ],
    ), (
      "OPSTX", // name
      vec![1, 1, 1], // secret
      "OOOOOOOO PPPPPPPP SSSSSSSS TTTTTTTT XXXXXXXX", // text
      vec![ // exp
        0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0xd0, 0x9e, 0x4f, 0x4f,
        0x20,
        0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50,
        0x20,
        0xd0, 0x85, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53,
        0x20,
        0xd0, 0xa2, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54,
        0x20,
        0xd0, 0xa5, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58,
      ],
    )];

    for (name, secret, text, exp) in tests {
      assert_eq!(encode_vec(&secret, text), Ok(exp), "{name}");
    }
  }

  #[test]
  fn test_capacity() {
    let tests = vec![
      ("", 0),
      ("aaaa", 0),
      ("aaaaaaaa aaaaaaaa", 0),
      ("aaaaaaaa aaaaaaaa aaaaaaa", 0),
      ("aaaaaaaa aaaaaaaa aaaaaaaa", 1),
      ("aaaaaaaa aaaaaaaa aaaaaaaa aa", 1),
      ("aaaaaaaa aaaaaaaa aaaaaaaa a", 1),
      ("aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa", 2),
      ("aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa ", 2),
    ];

    for (s, exp) in tests {
      assert_eq!(capacity(s), exp, "s = {s}");
    }
  }

  #[test]
  fn test_decode_vec_fail() {
    let invalid_len_str = String::from_utf8(vec![ // text
      0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0xd0, 0x9e, 0x4f, 0x4f,
      0x20,
      0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50,
      0x20,
      0xd0, 0x85, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53,
      0x20,
      0xd0, 0xa2, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54,
      0x20,
    ]).unwrap();

    let tests = vec![(
      "invalid tag", // name
      "aaaaaaaa aaaaaaaa aaaaaaaa", // text
      Err(Err::BadTag(0)),
    ), (
      "invalid length", // name
      invalid_len_str.as_str(),
      Err(Err::TruncatedSecret(2, 3)),
    )];

    for (name, text, exp) in tests {
      assert_eq!(decode_vec(text), exp, "{name}");
    }
  }

  #[test]
  fn test_decode_vec_pass() {
    let trips_str = String::from_utf8(vec![
      0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0xd0, 0x9e, 0x4f, 0x4f,
      0x20,
      0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50,
      0x20,
      0xd0, 0x85, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53,
      0x20,
      0xd0, 0xa2, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54,
      0x20,
      0xd0, 0xa5, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58,
    ]).unwrap();

    let tests = vec![(
      "none", // name
      "", // text
      Ok(Vec::<u8>::new()), // exp
    ), (
      "trips", // name
      trips_str.as_str(), // text
      Ok(vec![1, 1, 1]),
    )];

    for (name, text, exp) in tests {
      assert_eq!(decode_vec(text), exp, "{name}");
    }
  }
}