1use thiserror::Error;
9
10#[derive(Debug, Clone, PartialEq, Eq, Error)]
12#[error("{0}")]
13pub struct HexError(pub String);
14
15pub fn decrypt(cipher: &[u8], mut r: u16) -> (Vec<u8>, u16) {
25 let mut plain = Vec::with_capacity(cipher.len());
26 for &c in cipher {
27 plain.push(c ^ (r >> 8) as u8);
28 r = next_key(c, r);
29 }
30 (plain, r)
31}
32
33pub fn encrypt(plain: &[u8], mut r: u16) -> (Vec<u8>, u16) {
46 let mut cipher = Vec::with_capacity(plain.len());
47 for &p in plain {
48 let c = p ^ (r >> 8) as u8;
49 cipher.push(c);
50 r = next_key(c, r);
51 }
52 (cipher, r)
53}
54
55fn next_key(cipher: u8, r: u16) -> u16 {
56 ((cipher as u32 + r as u32)
57 .wrapping_mul(52845)
58 .wrapping_add(22719)
59 & 0xFFFF) as u16
60}
61
62pub fn hex_string(s: &[u8]) -> Vec<u8> {
64 const DIGITS: &[u8; 16] = b"0123456789abcdef";
65 let mut out = Vec::with_capacity(s.len() * 2);
66 for &b in s {
67 out.push(DIGITS[(b >> 4) as usize]);
68 out.push(DIGITS[(b & 0xF) as usize]);
69 }
70 out
71}
72
73pub fn de_hex_string(h: &[u8]) -> Result<Vec<u8>, HexError> {
76 let digits: Vec<u8> = h.iter().copied().filter(|b| !is_ascii_space(*b)).collect();
77 unhexlify(&digits)
78}
79
80pub fn is_ascii_space(b: u8) -> bool {
82 matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C)
83}
84
85pub fn unhexlify(digits: &[u8]) -> Result<Vec<u8>, HexError> {
87 if !digits.len().is_multiple_of(2) {
88 return Err(HexError("Odd-length string".into()));
89 }
90 let value = |b: u8| -> Result<u8, HexError> {
91 (b as char)
92 .to_digit(16)
93 .map(|d| d as u8)
94 .ok_or_else(|| HexError("Non-hexadecimal digit found".into()))
95 };
96 digits
97 .chunks(2)
98 .map(|pair| Ok(value(pair[0])? << 4 | value(pair[1])?))
99 .collect()
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
107 fn hex_round_trip() {
108 assert_eq!(hex_string(b"\x01\xab"), b"01ab");
109 assert_eq!(de_hex_string(b"01 A\nb"), Ok(b"\x01\xab".to_vec()));
110 assert!(de_hex_string(b"0").is_err());
111 assert!(de_hex_string(b"0g").is_err());
112 }
113}