Skip to main content

fontoxide_misc/
eexec.rs

1//! Port of `fontTools.misc.eexec`: the Type 1 charstring and `eexec` encryption.
2//!
3//! PostScript Type 1 fonts use the same cipher for the charstrings (initial key
4//! 4330) and for the `eexec` encrypted part of the font program (initial key
5//! 55665). The cipher uses feedback: the ciphertext modifies the key, so the
6//! functions here return the key at the end, for continuing later.
7
8use thiserror::Error;
9
10/// `binascii.Error`: hexadecimal data that cannot be decoded.
11#[derive(Debug, Clone, PartialEq, Eq, Error)]
12#[error("{0}")]
13pub struct HexError(pub String);
14
15/// Decrypts `cipher` with the initial key `r` (`decrypt`); returns the plaintext
16/// and the key for a subsequent decryption.
17///
18/// ```
19/// use fontoxide_misc::eexec::decrypt;
20/// let (plain, r) = decrypt(b"\0\0asdadads asds\xb5", 12321);
21/// assert_eq!(plain, b"0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1");
22/// assert_eq!(r, 36142);
23/// ```
24pub 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
33/// Encrypts `plain` with the initial key `r` (`encrypt`); returns the
34/// ciphertext and the key for a subsequent encryption.
35///
36/// Like fontTools, this does not add the random bytes the Type 1 specification
37/// prefixes the plaintext with.
38///
39/// ```
40/// use fontoxide_misc::eexec::encrypt;
41/// let (cipher, r) = encrypt(b"0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1", 12321);
42/// assert_eq!(cipher, b"\0\0asdadads asds\xb5");
43/// assert_eq!(r, 36142);
44/// ```
45pub 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
62/// `hexString`: `binascii.hexlify`, lowercase hexadecimal.
63pub 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
73/// `deHexString`: drops ASCII whitespace (`bytes.split()`), then
74/// `binascii.unhexlify`.
75pub 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
80/// Whitespace as `bytes.split()` sees it.
81pub fn is_ascii_space(b: u8) -> bool {
82	matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C)
83}
84
85/// `binascii.unhexlify`.
86pub 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}