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
use secrecy::ExposeSecret as _;
use x25519_dalek::{EphemeralSecret, PublicKey, SharedSecret, StaticSecret};

use super::{Error, Key, StrongBox};

const PRIVATE_KEY: u8 = 0;
const PUBLIC_KEY: u8 = 1;

pub struct SharedStrongBoxKey {
	key: Option<Key<StaticSecret>>,
	public: PublicKey,
}

impl std::fmt::Debug for SharedStrongBoxKey {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
		f.debug_struct("SharedStrongBoxKey")
			.field("public", &self.public())
			.finish()
	}
}

impl SharedStrongBoxKey {
	fn new() -> Self {
		Self::new_from_key(StaticSecret::random())
	}

	fn new_from_key(key: StaticSecret) -> Self {
		SharedStrongBoxKey {
			public: (&key).into(),
			key: Some(Key::new(key)),
		}
	}

	fn new_from_pubkey(key: [u8; 32]) -> Self {
		SharedStrongBoxKey {
			public: PublicKey::from(key),
			key: None,
		}
	}

	fn diffie_hellman(&self, pubkey: &PublicKey) -> Option<SharedSecret> {
		self.key
			.as_ref()
			.map(|k| k.expose_secret().diffie_hellman(pubkey))
	}

	pub fn private(&self) -> Option<Key<Vec<u8>>> {
		self.key.as_ref().map(|k| {
			let mut v = vec![PRIVATE_KEY];
			v.extend_from_slice(k.expose_secret().as_bytes());
			Key::new(v)
		})
	}

	pub fn public(&self) -> Vec<u8> {
		let mut v = vec![PUBLIC_KEY];

		v.extend_from_slice(self.public.as_bytes());

		v
	}
}

impl TryFrom<&Vec<u8>> for SharedStrongBoxKey {
	type Error = Error;

	fn try_from(k: &Vec<u8>) -> Result<Self, Error> {
		k[..].try_into()
	}
}

impl TryFrom<&[u8]> for SharedStrongBoxKey {
	type Error = Error;

	fn try_from(k: &[u8]) -> Result<Self, Error> {
		if k.len() != 33 {
			return Err(Error::invalid_key("invalid key length"));
		}

		let inkey: [u8; 32] = k[1..33].try_into().expect("failed to read key");

		match k.first() {
			Some(&PRIVATE_KEY) => Ok(SharedStrongBoxKey::new_from_key(StaticSecret::from(inkey))),
			Some(&PUBLIC_KEY) => Ok(SharedStrongBoxKey::new_from_pubkey(inkey)),
			Some(n) => Err(Error::invalid_key(format!("invalid type byte {n}"))),
			None => Err(Error::invalid_key("how the heck did we get here?!?")),
		}
	}
}

#[derive(Debug)]
pub struct SharedStrongBox {
	key: SharedStrongBoxKey,
}

impl SharedStrongBox {
	pub fn generate_key() -> SharedStrongBoxKey {
		SharedStrongBoxKey::new()
	}

	pub fn new(key: SharedStrongBoxKey) -> Self {
		Self { key }
	}

	pub fn encrypt(&self, plaintext: &[u8], ctx: &[u8]) -> Result<Vec<u8>, Error> {
		let tmp_key = EphemeralSecret::random();
		let tmp_pubkey: PublicKey = (&tmp_key).into();

		let box_key = tmp_key.diffie_hellman(&self.key.public);

		if !box_key.was_contributory() {
			return Err(Error::Encryption);
		}

		let mut aad = Vec::<u8>::new();
		aad.extend_from_slice(ctx);
		aad.extend_from_slice(tmp_pubkey.as_bytes());

		let strong_box = StrongBox::new(Key::new(box_key.to_bytes()), Vec::<[u8; 32]>::new());
		let ciphertext = strong_box.encrypt(plaintext, &aad)?;

		Ciphertext::new(tmp_pubkey.to_bytes(), ciphertext).to_bytes()
	}

	pub fn decrypt(&self, ciphertext: &[u8], ctx: &[u8]) -> Result<Vec<u8>, Error> {
		let ciphertext = Ciphertext::try_from(ciphertext)?;

		let box_key = self
			.key
			.diffie_hellman(&PublicKey::from(ciphertext.pubkey))
			.ok_or_else(|| {
				Error::invalid_key("this SharedStrongBox does not have a private key")
			})?;

		if !box_key.was_contributory() {
			return Err(Error::Encryption);
		}

		let box_key = box_key.to_bytes();

		let mut aad = Vec::<u8>::new();
		aad.extend_from_slice(ctx);
		aad.extend_from_slice(&ciphertext.pubkey);

		let strong_box = StrongBox::new(Key::new(box_key), vec![Key::new(box_key)]);

		strong_box.decrypt(&ciphertext.ciphertext, &aad)
	}
}

const CIPHERTEXT_MAGIC: [u8; 3] = [0xB2, 0xC6, 0xF5];

#[derive(Clone, Debug)]
struct Ciphertext {
	pubkey: [u8; 32],
	ciphertext: Vec<u8>,
}

impl Ciphertext {
	pub(crate) fn new(pubkey: [u8; 32], ciphertext: Vec<u8>) -> Self {
		Self { pubkey, ciphertext }
	}

	pub(crate) fn to_bytes(&self) -> Result<Vec<u8>, Error> {
		use ciborium_ll::{Encoder, Header};

		let mut v: Vec<u8> = Vec::new();

		v.extend_from_slice(&CIPHERTEXT_MAGIC);

		let mut enc = Encoder::from(&mut v);
		enc.push(Header::Array(Some(2)))
			.map_err(|e| Error::encoding("array", e))?;
		enc.bytes(&self.pubkey, None)
			.map_err(|e| Error::encoding("pubkey", e))?;
		enc.bytes(&self.ciphertext, None)
			.map_err(|e| Error::encoding("ciphertext", e))?;

		Ok(v)
	}
}

impl TryFrom<&[u8]> for Ciphertext {
	type Error = Error;

	fn try_from(b: &[u8]) -> Result<Self, Self::Error> {
		use ciborium_ll::{Decoder, Header};

		if b.len() < 37 {
			return Err(Error::invalid_ciphertext("too short"));
		}

		if b[0..3] != CIPHERTEXT_MAGIC {
			return Err(Error::invalid_ciphertext("incorrect magic"));
		}

		let mut dec = Decoder::from(&b[3..]);

		let Header::Array(Some(2)) = dec.pull().map_err(|e| Error::decoding("array", e))? else {
			return Err(Error::invalid_ciphertext("expected array"));
		};

		// CBOR's great, until you have to deal with segmented bytestrings...
		let Header::Bytes(len) = dec
			.pull()
			.map_err(|e| Error::decoding("pubkey header", e))?
		else {
			return Err(Error::invalid_ciphertext("expected pubkey"));
		};

		let mut segments = dec.bytes(len);

		let Ok(Some(mut segment)) = segments.pull() else {
			return Err(Error::invalid_ciphertext("bad pubkey"));
		};

		let mut buf = [0u8; 1024];
		let mut pubkey = [0u8; 32];

		if let Some(chunk) = segment
			.pull(&mut buf[..])
			.map_err(|e| Error::decoding("pubkey", e))?
		{
			if chunk.len() != pubkey.len() {
				return Err(Error::invalid_ciphertext("bad pubkey length"));
			}
			pubkey[..].copy_from_slice(chunk);
		} else {
			return Err(Error::invalid_ciphertext("short pubkey"));
		}

		// ibid.
		let Header::Bytes(len) = dec
			.pull()
			.map_err(|e| Error::decoding("ciphertext header", e))?
		else {
			return Err(Error::invalid_ciphertext("expected ciphertext"));
		};

		let mut segments = dec.bytes(len);

		let Ok(Some(mut segment)) = segments.pull() else {
			return Err(Error::invalid_ciphertext("bad ciphertext"));
		};

		let mut ciphertext: Vec<u8> = Vec::new();

		while let Some(chunk) = segment
			.pull(&mut buf[..])
			.map_err(|e| Error::decoding("ciphertext", e))?
		{
			ciphertext.extend_from_slice(chunk);
		}

		Ok(Self { pubkey, ciphertext })
	}
}