1use super::*;
2
3#[inline]
9pub fn auth_now_secs() -> u64 {
10 SystemTime::now()
11 .duration_since(UNIX_EPOCH)
12 .map(|dur: Duration| dur.as_secs())
13 .unwrap_or(0)
14}
15
16#[inline(always)]
27pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
28 req.get_headers()
29 .get(lower_key)
30 .and_then(|values: &RequestHeadersValue| values.back())
31 .map(String::as_str)
32}
33
34#[inline]
46pub(crate) fn sha256_finish_from(mut state: [u32; 8], prefix_bytes: u64, data: &[u8]) -> [u8; 32] {
47 let total_bytes: u64 = prefix_bytes.wrapping_add(data.len() as u64);
48 let bit_len: u64 = total_bytes.wrapping_mul(8);
49 let (blocks, rem_slice): (&[[u8; 64]], &[u8]) = data.as_chunks::<64>();
50 for block in blocks {
51 sha256_compress(&mut state, block);
52 }
53 let rem: usize = rem_slice.len();
54 let mut tail0: [u8; 64] = [0u8; 64];
55 tail0[..rem].copy_from_slice(rem_slice);
56 tail0[rem] = 0x80;
57 if rem < 56 {
58 tail0[56..64].copy_from_slice(&bit_len.to_be_bytes());
59 sha256_compress(&mut state, &tail0);
60 } else {
61 sha256_compress(&mut state, &tail0);
62 let mut tail1: [u8; 64] = [0u8; 64];
63 tail1[56..64].copy_from_slice(&bit_len.to_be_bytes());
64 sha256_compress(&mut state, &tail1);
65 }
66 let mut out: [u8; 32] = [0u8; 32];
67 let b0: [u8; 4] = state[0].to_be_bytes();
68 let b1: [u8; 4] = state[1].to_be_bytes();
69 let b2: [u8; 4] = state[2].to_be_bytes();
70 let b3: [u8; 4] = state[3].to_be_bytes();
71 let b4: [u8; 4] = state[4].to_be_bytes();
72 let b5: [u8; 4] = state[5].to_be_bytes();
73 let b6: [u8; 4] = state[6].to_be_bytes();
74 let b7: [u8; 4] = state[7].to_be_bytes();
75 out[0..4].copy_from_slice(&b0);
76 out[4..8].copy_from_slice(&b1);
77 out[8..12].copy_from_slice(&b2);
78 out[12..16].copy_from_slice(&b3);
79 out[16..20].copy_from_slice(&b4);
80 out[20..24].copy_from_slice(&b5);
81 out[24..28].copy_from_slice(&b6);
82 out[28..32].copy_from_slice(&b7);
83 out
84}
85
86#[inline]
96pub fn sha256(data: &[u8]) -> [u8; 32] {
97 sha256_finish_from(SHA256_INIT, 0, data)
98}
99
100#[inline(always)]
109pub(crate) fn sha256_step(
110 abcd: (u32, u32, u32, &mut u32),
111 efgh: (u32, u32, u32, &mut u32),
112 w: u32,
113 k: u32,
114) {
115 let (a, b, c, d): (u32, u32, u32, &mut u32) = abcd;
116 let (e, f, g, h): (u32, u32, u32, &mut u32) = efgh;
117 let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
118 let ch: u32 = (e & f) ^ ((!e) & g);
119 let t1: u32 = (*h)
120 .wrapping_add(s1)
121 .wrapping_add(ch)
122 .wrapping_add(k)
123 .wrapping_add(w);
124 let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
125 let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
126 *d = (*d).wrapping_add(t1);
127 *h = t1.wrapping_add(s0.wrapping_add(maj));
128}
129
130#[inline(always)]
143pub(crate) fn sha256_w_next(w0: u32, w1: u32, w9: u32, w14: u32) -> u32 {
144 let s0: u32 = w1.rotate_right(7) ^ w1.rotate_right(18) ^ (w1 >> 3);
145 let s1: u32 = w14.rotate_right(17) ^ w14.rotate_right(19) ^ (w14 >> 10);
146 w0.wrapping_add(s0).wrapping_add(w9).wrapping_add(s1)
147}
148
149#[inline(always)]
155pub(crate) fn sha256_expand_16(w: &mut [u32; 16]) {
156 w[0] = sha256_w_next(w[0], w[1], w[9], w[14]);
157 w[1] = sha256_w_next(w[1], w[2], w[10], w[15]);
158 w[2] = sha256_w_next(w[2], w[3], w[11], w[0]);
159 w[3] = sha256_w_next(w[3], w[4], w[12], w[1]);
160 w[4] = sha256_w_next(w[4], w[5], w[13], w[2]);
161 w[5] = sha256_w_next(w[5], w[6], w[14], w[3]);
162 w[6] = sha256_w_next(w[6], w[7], w[15], w[4]);
163 w[7] = sha256_w_next(w[7], w[8], w[0], w[5]);
164 w[8] = sha256_w_next(w[8], w[9], w[1], w[6]);
165 w[9] = sha256_w_next(w[9], w[10], w[2], w[7]);
166 w[10] = sha256_w_next(w[10], w[11], w[3], w[8]);
167 w[11] = sha256_w_next(w[11], w[12], w[4], w[9]);
168 w[12] = sha256_w_next(w[12], w[13], w[5], w[10]);
169 w[13] = sha256_w_next(w[13], w[14], w[6], w[11]);
170 w[14] = sha256_w_next(w[14], w[15], w[7], w[12]);
171 w[15] = sha256_w_next(w[15], w[0], w[8], w[13]);
172}
173
174#[inline(always)]
182pub(crate) fn sha256_rounds_16(v: &mut [u32; 8], w: &[u32; 16], k_base: usize) {
183 let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h]: [u32; 8] = *v;
184 sha256_step((a, b, c, &mut d), (e, f, g, &mut h), w[0], SHA256_K[k_base]);
185 sha256_step(
186 (h, a, b, &mut c),
187 (d, e, f, &mut g),
188 w[1],
189 SHA256_K[k_base + 1],
190 );
191 sha256_step(
192 (g, h, a, &mut b),
193 (c, d, e, &mut f),
194 w[2],
195 SHA256_K[k_base + 2],
196 );
197 sha256_step(
198 (f, g, h, &mut a),
199 (b, c, d, &mut e),
200 w[3],
201 SHA256_K[k_base + 3],
202 );
203 sha256_step(
204 (e, f, g, &mut h),
205 (a, b, c, &mut d),
206 w[4],
207 SHA256_K[k_base + 4],
208 );
209 sha256_step(
210 (d, e, f, &mut g),
211 (h, a, b, &mut c),
212 w[5],
213 SHA256_K[k_base + 5],
214 );
215 sha256_step(
216 (c, d, e, &mut f),
217 (g, h, a, &mut b),
218 w[6],
219 SHA256_K[k_base + 6],
220 );
221 sha256_step(
222 (b, c, d, &mut e),
223 (f, g, h, &mut a),
224 w[7],
225 SHA256_K[k_base + 7],
226 );
227 sha256_step(
228 (a, b, c, &mut d),
229 (e, f, g, &mut h),
230 w[8],
231 SHA256_K[k_base + 8],
232 );
233 sha256_step(
234 (h, a, b, &mut c),
235 (d, e, f, &mut g),
236 w[9],
237 SHA256_K[k_base + 9],
238 );
239 sha256_step(
240 (g, h, a, &mut b),
241 (c, d, e, &mut f),
242 w[10],
243 SHA256_K[k_base + 10],
244 );
245 sha256_step(
246 (f, g, h, &mut a),
247 (b, c, d, &mut e),
248 w[11],
249 SHA256_K[k_base + 11],
250 );
251 sha256_step(
252 (e, f, g, &mut h),
253 (a, b, c, &mut d),
254 w[12],
255 SHA256_K[k_base + 12],
256 );
257 sha256_step(
258 (d, e, f, &mut g),
259 (h, a, b, &mut c),
260 w[13],
261 SHA256_K[k_base + 13],
262 );
263 sha256_step(
264 (c, d, e, &mut f),
265 (g, h, a, &mut b),
266 w[14],
267 SHA256_K[k_base + 14],
268 );
269 sha256_step(
270 (b, c, d, &mut e),
271 (f, g, h, &mut a),
272 w[15],
273 SHA256_K[k_base + 15],
274 );
275 *v = [a, b, c, d, e, f, g, h];
276}
277
278pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
285 let mut w: [u32; 16] = [
286 u32::from_be_bytes([block[0], block[1], block[2], block[3]]),
287 u32::from_be_bytes([block[4], block[5], block[6], block[7]]),
288 u32::from_be_bytes([block[8], block[9], block[10], block[11]]),
289 u32::from_be_bytes([block[12], block[13], block[14], block[15]]),
290 u32::from_be_bytes([block[16], block[17], block[18], block[19]]),
291 u32::from_be_bytes([block[20], block[21], block[22], block[23]]),
292 u32::from_be_bytes([block[24], block[25], block[26], block[27]]),
293 u32::from_be_bytes([block[28], block[29], block[30], block[31]]),
294 u32::from_be_bytes([block[32], block[33], block[34], block[35]]),
295 u32::from_be_bytes([block[36], block[37], block[38], block[39]]),
296 u32::from_be_bytes([block[40], block[41], block[42], block[43]]),
297 u32::from_be_bytes([block[44], block[45], block[46], block[47]]),
298 u32::from_be_bytes([block[48], block[49], block[50], block[51]]),
299 u32::from_be_bytes([block[52], block[53], block[54], block[55]]),
300 u32::from_be_bytes([block[56], block[57], block[58], block[59]]),
301 u32::from_be_bytes([block[60], block[61], block[62], block[63]]),
302 ];
303 let mut v: [u32; 8] = *state;
304 sha256_rounds_16(&mut v, &w, 0);
305 sha256_expand_16(&mut w);
306 sha256_rounds_16(&mut v, &w, 16);
307 sha256_expand_16(&mut w);
308 sha256_rounds_16(&mut v, &w, 32);
309 sha256_expand_16(&mut w);
310 sha256_rounds_16(&mut v, &w, 48);
311 state[0] = state[0].wrapping_add(v[0]);
312 state[1] = state[1].wrapping_add(v[1]);
313 state[2] = state[2].wrapping_add(v[2]);
314 state[3] = state[3].wrapping_add(v[3]);
315 state[4] = state[4].wrapping_add(v[4]);
316 state[5] = state[5].wrapping_add(v[5]);
317 state[6] = state[6].wrapping_add(v[6]);
318 state[7] = state[7].wrapping_add(v[7]);
319}
320
321#[inline]
332pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
333 HmacSha256Key::new(key).mac(data)
334}
335
336#[inline]
347pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
348 if a.len() != b.len() {
349 return false;
350 }
351 let mut diff: u8 = 0;
352 for i in 0..a.len() {
353 diff |= a[i] ^ b[i];
354 }
355 diff == 0
356}
357
358#[inline]
365pub(crate) fn base64url_encode_into(input: &[u8], out: &mut Vec<u8>) {
366 let encoded_len: usize = (input.len() * 4).div_ceil(3);
367 out.reserve(encoded_len);
368 let (triples, rem): (&[[u8; 3]], &[u8]) = input.as_chunks::<3>();
369 for chunk in triples {
370 let triple: u32 = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | (chunk[2] as u32);
371 out.extend_from_slice(&[
372 BASE64URL_ALPHABET[((triple >> 18) & 0x3F) as usize],
373 BASE64URL_ALPHABET[((triple >> 12) & 0x3F) as usize],
374 BASE64URL_ALPHABET[((triple >> 6) & 0x3F) as usize],
375 BASE64URL_ALPHABET[(triple & 0x3F) as usize],
376 ]);
377 }
378 if rem.len() == 1 {
379 let val: u32 = (rem[0] as u32) << 16;
380 out.extend_from_slice(&[
381 BASE64URL_ALPHABET[((val >> 18) & 0x3F) as usize],
382 BASE64URL_ALPHABET[((val >> 12) & 0x3F) as usize],
383 ]);
384 } else if rem.len() == 2 {
385 let val: u32 = ((rem[0] as u32) << 16) | ((rem[1] as u32) << 8);
386 out.extend_from_slice(&[
387 BASE64URL_ALPHABET[((val >> 18) & 0x3F) as usize],
388 BASE64URL_ALPHABET[((val >> 12) & 0x3F) as usize],
389 BASE64URL_ALPHABET[((val >> 6) & 0x3F) as usize],
390 ]);
391 }
392}
393
394#[inline]
404pub fn base64url_encode(input: &[u8]) -> String {
405 let mut buf: Vec<u8> = Vec::with_capacity((input.len() * 4).div_ceil(3));
406 base64url_encode_into(input, &mut buf);
407 String::from_utf8(buf).unwrap_or_default()
408}
409
410#[inline]
422pub(crate) fn decode_base64_into(bytes: &[u8], table: &[u8; 256], out: &mut [u8]) -> Option<usize> {
423 if bytes.len() % 4 == 1 {
424 return None;
425 }
426 let decoded_len: usize = (bytes.len() * 3) / 4;
427 if out.len() < decoded_len {
428 return None;
429 }
430 let mut pos: usize = 0;
431 let (quads, rem): (&[[u8; 4]], &[u8]) = bytes.as_chunks::<4>();
432 for chunk in quads {
433 let a: u8 = table[chunk[0] as usize];
434 let b: u8 = table[chunk[1] as usize];
435 let c: u8 = table[chunk[2] as usize];
436 let d: u8 = table[chunk[3] as usize];
437 let ab: u8 = a | b;
438 let cd: u8 = c | d;
439 if ((ab | cd) & 0x80) != 0 {
440 return None;
441 }
442 let quad: u32 = ((a as u32) << 18) | ((b as u32) << 12) | ((c as u32) << 6) | (d as u32);
443 out[pos] = ((quad >> 16) & 0xFF) as u8;
444 out[pos + 1] = ((quad >> 8) & 0xFF) as u8;
445 out[pos + 2] = (quad & 0xFF) as u8;
446 pos += 3;
447 }
448 if rem.len() == 2 {
449 let a: u8 = table[rem[0] as usize];
450 let b: u8 = table[rem[1] as usize];
451 if ((a | b) & 0x80) != 0 {
452 return None;
453 }
454 let val: u32 = ((a as u32) << 18) | ((b as u32) << 12);
455 out[pos] = ((val >> 16) & 0xFF) as u8;
456 pos += 1;
457 } else if rem.len() == 3 {
458 let a: u8 = table[rem[0] as usize];
459 let b: u8 = table[rem[1] as usize];
460 let c: u8 = table[rem[2] as usize];
461 let ab: u8 = a | b;
462 if ((ab | c) & 0x80) != 0 {
463 return None;
464 }
465 let val: u32 = ((a as u32) << 18) | ((b as u32) << 12) | ((c as u32) << 6);
466 out[pos] = ((val >> 16) & 0xFF) as u8;
467 out[pos + 1] = ((val >> 8) & 0xFF) as u8;
468 pos += 2;
469 }
470 Some(pos)
471}
472
473#[inline]
483pub(crate) fn decode_base64url_32(input: &str) -> Option<[u8; 32]> {
484 let trimmed: &[u8] = input.trim_end_matches('=').as_bytes();
485 if trimmed.len() != HMAC_SIG_B64_LEN {
486 return None;
487 }
488 let mut out: [u8; 32] = [0u8; 32];
489 let written: usize = decode_base64_into(trimmed, &BASE64URL_DECODE_TABLE, &mut out)?;
490 if written == 32 { Some(out) } else { None }
491}
492
493#[inline]
504pub(crate) fn decode_base64_inner(input: &str, url_safe: bool) -> Option<Vec<u8>> {
505 let bytes: &[u8] = input.trim_end_matches('=').as_bytes();
506 if bytes.len() % 4 == 1 {
507 return None;
508 }
509 let table: &[u8; 256] = if url_safe {
510 &BASE64URL_DECODE_TABLE
511 } else {
512 &BASE64_STD_DECODE_TABLE
513 };
514 let decoded_len: usize = (bytes.len() * 3) / 4;
515 let mut out: Vec<u8> = vec![0u8; decoded_len];
516 let written: usize = decode_base64_into(bytes, table, &mut out)?;
517 out.truncate(written);
518 Some(out)
519}
520
521#[inline]
531pub fn base64url_decode(input: &str) -> Option<Vec<u8>> {
532 decode_base64_inner(input, true)
533}
534
535#[inline]
545pub fn base64_decode(input: &str) -> Option<Vec<u8>> {
546 decode_base64_inner(input, false)
547}
548
549#[inline]
560pub(crate) fn strip_auth_scheme<'a>(header: &'a str, lowercase_prefix: &str) -> Option<&'a str> {
561 let trimmed: &'a str = header.trim();
562 if trimmed.len() < lowercase_prefix.len() {
563 return None;
564 }
565 let (head, tail): (&'a str, &'a str) = trimmed.split_at(lowercase_prefix.len());
566 if head.eq_ignore_ascii_case(lowercase_prefix) {
567 let token: &'a str = tail.trim();
568 if token.is_empty() { None } else { Some(token) }
569 } else {
570 None
571 }
572}
573
574pub(crate) fn encode_hs256_header_b64(default_kid: Option<&str>) -> String {
584 let Some(kid) = default_kid else {
585 return DEFAULT_HS256_HEADER_B64.to_owned();
586 };
587 let header: JwtHeader = JwtHeader {
588 alg: JWT_ALG_HS256.to_owned(),
589 typ: Some(JWT_TYP_JWT.to_owned()),
590 kid: Some(kid.to_owned()),
591 };
592 let json_bytes: Vec<u8> = to_vec(&header).unwrap_or_default();
593 base64url_encode(&json_bytes)
594}