1use aes_gcm::aead::{AeadInPlace, KeyInit};
8use aes_gcm::{Aes128Gcm, Nonce};
9use hkdf::Hkdf;
10use p256::elliptic_curve::sec1::ToEncodedPoint;
11use p256::{PublicKey, SecretKey};
12use sha2::Sha256;
13
14use crate::{Error, Result};
15
16pub const HEADER_LEN: usize = 86;
18const TAG_LEN: usize = 16;
19pub const BODY_LEN: usize = 3000;
21pub const MAX_PLAINTEXT: usize = BODY_LEN - HEADER_LEN - TAG_LEN - 1;
23const RECORD_SIZE: u32 = 4096;
24
25pub fn encrypt(ua_public: &[u8], auth: &[u8], plaintext: &[u8]) -> Result<Vec<u8>> {
27 let sender = SecretKey::random(&mut rand::rngs::OsRng);
28 encrypt_with(ua_public, auth, plaintext, &sender, crate::random::<16>(), BODY_LEN)
29}
30
31fn encrypt_with(
32 ua_public: &[u8],
33 auth: &[u8],
34 plaintext: &[u8],
35 sender: &SecretKey,
36 salt: [u8; 16],
37 body_len: usize,
38) -> Result<Vec<u8>> {
39 if auth.len() != 16 {
40 return Err(Error::Key("auth secret must be 16 bytes"));
41 }
42 if plaintext.len() > body_len - HEADER_LEN - TAG_LEN - 1 {
43 return Err(Error::Format("notification too large".into()));
44 }
45 let ua = PublicKey::from_sec1_bytes(ua_public).map_err(|_| Error::Key("bad p256dh key"))?;
46 let ua_bytes = ua.to_encoded_point(false);
47 let as_public = sender.public_key().to_encoded_point(false);
48 let shared = p256::ecdh::diffie_hellman(sender.to_nonzero_scalar(), ua.as_affine());
49 let (cek, nonce) = derive(shared.raw_secret_bytes(), auth, ua_bytes.as_bytes(), as_public.as_bytes(), &salt)?;
50
51 let mut record = Vec::with_capacity(body_len - HEADER_LEN);
52 record.extend_from_slice(plaintext);
53 record.push(0x02);
54 record.resize(body_len - HEADER_LEN - TAG_LEN, 0);
55 let tag = Aes128Gcm::new(&cek.into())
56 .encrypt_in_place_detached(&Nonce::from(nonce), &[], &mut record)
57 .map_err(|_| Error::Crypto("encryption failed"))?;
58
59 let mut body = Vec::with_capacity(body_len);
60 body.extend_from_slice(&salt);
61 body.extend_from_slice(&RECORD_SIZE.to_be_bytes());
62 body.push(65);
63 body.extend_from_slice(as_public.as_bytes());
64 body.extend_from_slice(&record);
65 body.extend_from_slice(&tag);
66 Ok(body)
67}
68
69pub fn decrypt(ua_secret: &SecretKey, auth: &[u8], body: &[u8]) -> Result<Vec<u8>> {
72 if body.len() < HEADER_LEN + TAG_LEN + 1 || body[20] != 65 {
73 return Err(Error::Format("bad aes128gcm header".into()));
74 }
75 let salt: [u8; 16] = body[..16].try_into().unwrap();
76 let as_public = &body[21..86];
77 let sender = PublicKey::from_sec1_bytes(as_public).map_err(|_| Error::Key("bad sender key"))?;
78 let ua_public = ua_secret.public_key().to_encoded_point(false);
79 let shared = p256::ecdh::diffie_hellman(ua_secret.to_nonzero_scalar(), sender.as_affine());
80 let (cek, nonce) = derive(shared.raw_secret_bytes(), auth, ua_public.as_bytes(), as_public, &salt)?;
81
82 let (ciphertext, tag) = body[HEADER_LEN..].split_at(body.len() - HEADER_LEN - TAG_LEN);
83 let mut record = ciphertext.to_vec();
84 Aes128Gcm::new(&cek.into())
85 .decrypt_in_place_detached(&Nonce::from(nonce), &[], &mut record, tag.into())
86 .map_err(|_| Error::Crypto("decryption failed"))?;
87 let end = record.iter().rposition(|&b| b != 0).ok_or(Error::Format("no padding delimiter".into()))?;
88 if record[end] != 0x02 {
89 return Err(Error::Format("not a final record".into()));
90 }
91 record.truncate(end);
92 Ok(record)
93}
94
95fn derive(ecdh: &[u8], auth: &[u8], ua_public: &[u8], as_public: &[u8], salt: &[u8; 16]) -> Result<([u8; 16], [u8; 12])> {
96 let mut key_info = Vec::with_capacity(14 + 130);
97 key_info.extend_from_slice(b"WebPush: info\0");
98 key_info.extend_from_slice(ua_public);
99 key_info.extend_from_slice(as_public);
100 let mut ikm = [0u8; 32];
101 Hkdf::<Sha256>::new(Some(auth), ecdh)
102 .expand(&key_info, &mut ikm)
103 .map_err(|_| Error::Crypto("hkdf"))?;
104
105 let prk = Hkdf::<Sha256>::new(Some(salt), &ikm);
106 let mut cek = [0u8; 16];
107 let mut nonce = [0u8; 12];
108 prk.expand(b"Content-Encoding: aes128gcm\0", &mut cek).map_err(|_| Error::Crypto("hkdf"))?;
109 prk.expand(b"Content-Encoding: nonce\0", &mut nonce).map_err(|_| Error::Crypto("hkdf"))?;
110 Ok((cek, nonce))
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116 use crate::{b64url, unb64url};
117
118 const PLAINTEXT: &str = "When I grow up, I want to be a watermelon";
120 const AS_PRIVATE: &str = "yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw";
121 const UA_PUBLIC: &str = "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4";
122 const UA_PRIVATE: &str = "q1dXpw3UpT5VOmu_cf_v6ih07Aems3njxI-JWgLcM94";
123 const AUTH: &str = "BTBZMqHH6r4Tts7J_aSIgg";
124 const SALT: &str = "DGv6ra1nlYgDCS1FRnbzlw";
125 const BODY: &str = "DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPTpK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN";
126
127 #[test]
128 fn matches_the_rfc_example() {
129 let sender = SecretKey::from_slice(&unb64url(AS_PRIVATE).unwrap()).unwrap();
130 let salt: [u8; 16] = unb64url(SALT).unwrap().try_into().unwrap();
131 let body = encrypt_with(
132 &unb64url(UA_PUBLIC).unwrap(),
133 &unb64url(AUTH).unwrap(),
134 PLAINTEXT.as_bytes(),
135 &sender,
136 salt,
137 144,
138 )
139 .unwrap();
140 assert_eq!(b64url(&body), BODY);
141 }
142
143 #[test]
144 fn opens_the_rfc_example() {
145 let ua = SecretKey::from_slice(&unb64url(UA_PRIVATE).unwrap()).unwrap();
146 let out = decrypt(&ua, &unb64url(AUTH).unwrap(), &unb64url(BODY).unwrap()).unwrap();
147 assert_eq!(out, PLAINTEXT.as_bytes());
148 }
149
150 #[test]
151 fn every_body_is_the_same_size() {
152 let ua = SecretKey::random(&mut rand::rngs::OsRng);
153 let ua_public = ua.public_key().to_encoded_point(false);
154 let auth = crate::random::<16>();
155 for text in ["", "hi", &"x".repeat(MAX_PLAINTEXT)] {
156 let body = encrypt(ua_public.as_bytes(), &auth, text.as_bytes()).unwrap();
157 assert_eq!(body.len(), BODY_LEN);
158 assert_eq!(decrypt(&ua, &auth, &body).unwrap(), text.as_bytes());
159 }
160 assert!(encrypt(ua_public.as_bytes(), &auth, "x".repeat(MAX_PLAINTEXT + 1).as_bytes()).is_err());
161 }
162
163 #[test]
164 fn a_wrong_auth_secret_fails() {
165 let ua = SecretKey::random(&mut rand::rngs::OsRng);
166 let ua_public = ua.public_key().to_encoded_point(false);
167 let body = encrypt(ua_public.as_bytes(), &[1; 16], b"hi").unwrap();
168 assert!(decrypt(&ua, &[2; 16], &body).is_err());
169 }
170}