1use std::fmt;
7
8use aes_gcm::{AeadInOut, Aes256Gcm, KeyInit};
9use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
10use curve25519_dalek::montgomery::MontgomeryPoint;
11use heika_core::key::{PrivateKey, PublicKey};
12use hmac::digest::FixedOutput;
13use hmac::{Hmac, Mac};
14use rand_core::CryptoRng;
15use sha2::{Digest, Sha256, Sha512};
16use zeroize::Zeroizing;
17
18pub const TAG_SIZE: usize = 16;
20pub const IV_SIZE: usize = 12;
22
23pub struct SharedKey(Zeroizing<[u8; 32]>);
25
26impl SharedKey {
27 pub fn derive(
33 private_key: &PrivateKey,
34 other_public_key: &PublicKey,
35 ) -> Result<Self, InvalidPublicKey> {
36 let point = decode(&other_public_key.0).ok_or(InvalidPublicKey)?;
37 let mut multiplier = Zeroizing::new([0; 32]);
38 multiplier.copy_from_slice(&Sha512::digest(private_key.as_bytes())[..32]);
39 let product = Zeroizing::new(point.mul_clamped(*multiplier));
40 let shared_secret = Zeroizing::new(product.compress());
41 Ok(Self(hkdf(shared_secret.as_bytes())))
42 }
43
44 pub fn as_bytes(&self) -> &[u8; 32] {
45 &self.0
46 }
47}
48
49impl fmt::Debug for SharedKey {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 f.write_str("SharedKey(..)")
52 }
53}
54
55pub fn x25519_private_key(private_key: &PrivateKey) -> Zeroizing<[u8; 32]> {
60 let mut scalar = Zeroizing::new([0; 32]);
61 scalar.copy_from_slice(&Sha512::digest(private_key.as_bytes())[..32]);
62 scalar[0] &= 248;
63 scalar[31] &= 127;
64 scalar[31] |= 64;
65 scalar
66}
67
68pub fn x25519_public_key(public_key: &PublicKey) -> Result<[u8; 32], InvalidPublicKey> {
70 Ok(decode(&public_key.0)
71 .ok_or(InvalidPublicKey)?
72 .to_montgomery()
73 .to_bytes())
74}
75
76impl SharedKey {
77 pub fn candidates_from_x25519(shared: &[u8; 32]) -> Option<[Self; 2]> {
82 let point = MontgomeryPoint(*shared);
83 let candidate = |sign| {
84 point
85 .to_edwards(sign)
86 .map(|point| Self(hkdf(Zeroizing::new(point.compress()).as_bytes())))
87 };
88 Some([candidate(0)?, candidate(1)?])
89 }
90}
91
92pub fn encrypt(key: &SharedKey, iv: &[u8; IV_SIZE], plaintext: &[u8]) -> Vec<u8> {
94 let mut encrypted = vec![0; TAG_SIZE + IV_SIZE + plaintext.len()];
95 let (head, ciphertext) = encrypted.split_at_mut(TAG_SIZE + IV_SIZE);
96 ciphertext.copy_from_slice(plaintext);
97 let tag = cipher(key)
98 .encrypt_inout_detached(iv.into(), &[], ciphertext.into())
99 .expect("the plaintext fits in AES-GCM");
100 head[..TAG_SIZE].copy_from_slice(&tag);
101 head[TAG_SIZE..].copy_from_slice(iv);
102 encrypted
103}
104
105pub fn decrypt(key: &SharedKey, encrypted: &[u8]) -> Result<Zeroizing<Vec<u8>>, DecryptError> {
107 if encrypted.len() < TAG_SIZE + IV_SIZE {
108 return Err(DecryptError::TooShort);
109 }
110 let (tag, rest) = encrypted.split_at(TAG_SIZE);
111 let (iv, ciphertext) = rest.split_at(IV_SIZE);
112 let mut plaintext = Zeroizing::new(ciphertext.to_vec());
113 cipher(key)
114 .decrypt_inout_detached(
115 iv.try_into().expect("split at IV_SIZE"),
116 &[],
117 plaintext.as_mut_slice().into(),
118 tag.try_into().expect("split at TAG_SIZE"),
119 )
120 .map_err(|_| DecryptError::Failed)?;
121 Ok(plaintext)
122}
123
124pub fn seal<R: CryptoRng + ?Sized>(
128 rng: &mut R,
129 recipient_public_key: &PublicKey,
130 plaintext: &[u8],
131) -> Result<Vec<u8>, InvalidPublicKey> {
132 let ephemeral_key = PrivateKey::generate_with_rng(rng);
133 let mut iv = [0; IV_SIZE];
134 rng.fill_bytes(&mut iv);
135 let key = SharedKey::derive(&ephemeral_key, recipient_public_key)?;
136 let mut sealed = PublicKey::from_private_key(&ephemeral_key).0.to_vec();
137 sealed.extend_from_slice(&encrypt(&key, &iv, plaintext));
138 Ok(sealed)
139}
140
141pub fn open(private_key: &PrivateKey, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, DecryptError> {
143 let (ephemeral_public_key, encrypted) = sealed
144 .split_first_chunk::<32>()
145 .ok_or(DecryptError::TooShort)?;
146 let key = SharedKey::derive(private_key, &PublicKey(*ephemeral_public_key))
147 .map_err(|_| DecryptError::InvalidPublicKey)?;
148 decrypt(&key, encrypted)
149}
150
151pub fn sealed_ephemeral_key(sealed: &[u8]) -> Result<PublicKey, DecryptError> {
153 sealed
154 .first_chunk::<32>()
155 .map(|key| PublicKey(*key))
156 .ok_or(DecryptError::TooShort)
157}
158
159pub fn open_x25519(shared: &[u8; 32], sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, DecryptError> {
162 let (_, encrypted) = sealed
163 .split_first_chunk::<32>()
164 .ok_or(DecryptError::TooShort)?;
165 let candidates =
166 SharedKey::candidates_from_x25519(shared).ok_or(DecryptError::InvalidPublicKey)?;
167 candidates
168 .iter()
169 .find_map(|key| decrypt(key, encrypted).ok())
170 .ok_or(DecryptError::Failed)
171}
172
173fn cipher(key: &SharedKey) -> Aes256Gcm {
174 Aes256Gcm::new(key.as_bytes().into())
175}
176
177fn hkdf(shared_secret: &[u8; 32]) -> Zeroizing<[u8; 32]> {
179 let pseudo_random_key = hmac_sha256(&[0; 32], &[shared_secret]);
180 hmac_sha256(&pseudo_random_key[..], &[b"catapult", &[1]])
181}
182
183pub(crate) fn hmac_sha256(key: &[u8], data: &[&[u8]]) -> Zeroizing<[u8; 32]> {
184 let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC takes a key of any length");
185 for part in data {
186 mac.update(part);
187 }
188 let mut output = Zeroizing::new([0; 32]);
189 mac.finalize_into(
190 (&mut output[..])
191 .try_into()
192 .expect("SHA-256 outputs 32 bytes"),
193 );
194 output
195}
196
197fn decode(bytes: &[u8; 32]) -> Option<EdwardsPoint> {
200 if !is_canonical(bytes) {
201 return None;
202 }
203 CompressedEdwardsY(*bytes)
204 .decompress()
205 .filter(EdwardsPoint::is_torsion_free)
206}
207
208fn is_canonical(bytes: &[u8; 32]) -> bool {
210 bytes[0] < 0xED || bytes[1..31].iter().any(|&byte| byte != 0xFF) || bytes[31] & 0x7F != 0x7F
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct InvalidPublicKey;
216
217impl fmt::Display for InvalidPublicKey {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 f.write_str("公開鍵が、鍵の共有に使える曲線上の点ではありません")
220 }
221}
222
223impl std::error::Error for InvalidPublicKey {}
224
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub enum DecryptError {
227 TooShort,
229 InvalidPublicKey,
231 Failed,
233}
234
235impl fmt::Display for DecryptError {
236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237 match self {
238 Self::TooShort => f.write_str("暗号文が短すぎます"),
239 Self::InvalidPublicKey => f.write_str("使い捨ての公開鍵が曲線上の点ではありません"),
240 Self::Failed => f.write_str("復号できませんでした。鍵が違うか、改ざんされています"),
241 }
242 }
243}
244
245impl std::error::Error for DecryptError {}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250 use crate::testing::Replay;
251
252 const ALICE: &str = "9D61B19DEFFD5A60BA844AF492EC2CC44449C5697B326919703BAC031CAE7F60";
254 const BOB: &str = "4CCD089B28FF96DA9DB6C346EC114E0F5B8A319F35ABA624DA8CF6ED4FB8A6FB";
255
256 fn key(text: &str) -> (PrivateKey, PublicKey) {
257 let private_key: PrivateKey = text.parse().unwrap();
258 let public_key = PublicKey::from_private_key(&private_key);
259 (private_key, public_key)
260 }
261
262 fn x25519(private_key: &[u8; 32], public_key: &[u8; 32]) -> [u8; 32] {
264 MontgomeryPoint(*public_key)
265 .mul_clamped(*private_key)
266 .to_bytes()
267 }
268
269 #[test]
270 fn opens_with_the_result_of_x25519() {
271 let (bob, bob_public) = key(BOB);
272 for byte in 0..8u8 {
274 let randomness = [byte; 32 + IV_SIZE];
275 let sealed = seal(&mut Replay(&randomness), &bob_public, b"hello").unwrap();
276 let ephemeral = sealed_ephemeral_key(&sealed).unwrap();
277 let shared = x25519(
278 &x25519_private_key(&bob),
279 &x25519_public_key(&ephemeral).unwrap(),
280 );
281 assert_eq!(&*open_x25519(&shared, &sealed).unwrap(), b"hello");
282 let (alice, _) = key(ALICE);
284 let wrong = x25519(
285 &x25519_private_key(&alice),
286 &x25519_public_key(&ephemeral).unwrap(),
287 );
288 assert_eq!(
289 open_x25519(&wrong, &sealed).unwrap_err(),
290 DecryptError::Failed
291 );
292 }
293 }
294
295 #[test]
296 fn the_x25519_public_key_belongs_to_the_x25519_private_key() {
297 let (bob, bob_public) = key(BOB);
298 let base = curve25519_dalek::constants::X25519_BASEPOINT.to_bytes();
299 assert_eq!(
300 x25519(&x25519_private_key(&bob), &base),
301 x25519_public_key(&bob_public).unwrap()
302 );
303 }
304
305 #[test]
306 fn both_sides_derive_the_same_key() {
307 let (alice, alice_public) = key(ALICE);
308 let (bob, bob_public) = key(BOB);
309 let from_alice = SharedKey::derive(&alice, &bob_public).unwrap();
310 let from_bob = SharedKey::derive(&bob, &alice_public).unwrap();
311 assert_eq!(from_alice.as_bytes(), from_bob.as_bytes());
312 }
313
314 #[test]
315 fn hkdf_matches_rfc_5869_with_catapult_parameters() {
316 let secret = [0x42; 32];
317 let mut expected = [0; 32];
318 hkdf::Hkdf::<Sha256>::new(Some(&[0; 32]), &secret)
319 .expand(b"catapult", &mut expected)
320 .unwrap();
321 assert_eq!(*hkdf(&secret), expected);
322 }
323
324 #[test]
325 fn rejects_public_keys_that_are_not_usable_points() {
326 let (alice, _) = key(ALICE);
327 let mut order_two = [0xFF; 32];
328 order_two[0] = 0xEC;
329 order_two[31] = 0x7F;
330 let mut non_canonical = [0xFF; 32];
331 non_canonical[0] = 0xED;
332 non_canonical[31] = 0x7F;
333 let mut not_on_curve = [0; 32];
334 not_on_curve[0] = 2;
335 for (name, bytes) in [
336 ("order two", order_two),
338 ("non canonical", non_canonical),
340 ("not on curve", not_on_curve),
341 ] {
342 assert_eq!(
343 SharedKey::derive(&alice, &PublicKey(bytes)).unwrap_err(),
344 InvalidPublicKey,
345 "{name}"
346 );
347 }
348 }
349
350 #[test]
351 fn encrypts_in_the_catapult_layout() {
352 let (alice, _) = key(ALICE);
353 let (_, bob_public) = key(BOB);
354 let key = SharedKey::derive(&alice, &bob_public).unwrap();
355 let iv = [7; IV_SIZE];
356 let encrypted = encrypt(&key, &iv, b"hello");
357 assert_eq!(encrypted.len(), TAG_SIZE + IV_SIZE + 5);
358 assert_eq!(encrypted[TAG_SIZE..TAG_SIZE + IV_SIZE], iv);
359 assert_eq!(*decrypt(&key, &encrypted).unwrap(), b"hello");
360 }
361
362 #[test]
363 fn seals_with_the_given_rng_and_opens_with_the_recipient_key() {
364 let (bob, bob_public) = key(BOB);
365 let randomness = [0x11; 32 + IV_SIZE];
366 let sealed = seal(&mut Replay(&randomness), &bob_public, b"secret").unwrap();
367 let (_, ephemeral_public) = key(&"11".repeat(32));
368 assert_eq!(sealed[..32], ephemeral_public.0);
369 assert_eq!(
370 sealed[32 + TAG_SIZE..32 + TAG_SIZE + IV_SIZE],
371 [0x11; IV_SIZE]
372 );
373 assert_eq!(*open(&bob, &sealed).unwrap(), b"secret");
374 }
375
376 #[test]
377 fn refuses_another_key_or_a_changed_byte() {
378 let (_, bob_public) = key(BOB);
379 let (alice, _) = key(ALICE);
380 let randomness = [0x11; 32 + IV_SIZE];
381 let sealed = seal(&mut Replay(&randomness), &bob_public, b"secret").unwrap();
382 assert_eq!(open(&alice, &sealed).unwrap_err(), DecryptError::Failed);
383 let (bob, _) = key(BOB);
384 for index in [32, 32 + TAG_SIZE, sealed.len() - 1] {
385 let mut changed = sealed.clone();
386 changed[index] ^= 1;
387 assert_eq!(
388 open(&bob, &changed).unwrap_err(),
389 DecryptError::Failed,
390 "byte {index}"
391 );
392 }
393 }
394
395 #[test]
396 fn refuses_what_is_too_short() {
397 let (bob, _) = key(BOB);
398 assert_eq!(open(&bob, &[0; 31]).unwrap_err(), DecryptError::TooShort);
399 let mut sealed = PublicKey::from_private_key(&bob).0.to_vec();
400 sealed.extend_from_slice(&[0; TAG_SIZE + IV_SIZE - 1]);
401 assert_eq!(open(&bob, &sealed).unwrap_err(), DecryptError::TooShort);
402 }
403
404 #[test]
405 fn debug_hides_the_shared_key() {
406 let (alice, _) = key(ALICE);
407 let (_, bob_public) = key(BOB);
408 let key = SharedKey::derive(&alice, &bob_public).unwrap();
409 assert_eq!(format!("{key:?}"), "SharedKey(..)");
410 }
411}