Skip to content

Commit

Permalink
ProtectedHeader: add generate_aad function
Browse files Browse the repository at this point in the history
Due to RFC7516, aad used in AEAD is derived from ProtectedHeader. This
function does this.

Signed-off-by: Xynnn007 <xynnn@linux.alibaba.com>
  • Loading branch information
Xynnn007 committed Dec 10, 2024
1 parent 1d918fa commit ee031a4
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
extern crate alloc;

#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::{collections::btree_map::BTreeMap, string::String};
use alloc::{collections::btree_map::BTreeMap, string::String, vec::Vec};
use base64::{prelude::BASE64_URL_SAFE_NO_PAD, Engine};
use serde_json::Value;
#[cfg(all(feature = "std", not(feature = "alloc")))]
Expand Down Expand Up @@ -98,6 +98,16 @@ pub struct ProtectedHeader {
pub other_fields: BTreeMap<String, String>,
}

impl ProtectedHeader {
/// The generation of AAD for JWE follows [A.3.5 RFC7516](https://www.rfc-editor.org/rfc/rfc7516#appendix-A.3.5)
pub fn generate_aad(&self) -> Vec<u8> {
let protected_utf8 =
serde_json::to_string(&self).expect("unexpected OOM when serializing ProtectedHeader");
let aad = BASE64_URL_SAFE_NO_PAD.encode(protected_utf8);
aad.into_bytes()
}
}

fn serialize_base64_protected_header<S>(
sub: &ProtectedHeader,
serializer: S,
Expand Down Expand Up @@ -222,6 +232,9 @@ mod tests {

use crate::*;

#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::{collections::btree_map::BTreeMap, string::ToString};

#[test]
fn parse_request() {
let data = r#"
Expand Down Expand Up @@ -252,6 +265,22 @@ mod tests {
assert_eq!(challenge.extra_params, "");
}

#[test]
fn protected_header_generate_aad() {
let protected_header = ProtectedHeader {
alg: "fakealg".to_string(),
enc: "fakeenc".to_string(),
other_fields: BTreeMap::new(),
};

let aad = protected_header.generate_aad();

assert_eq!(
aad,
"eyJhbGciOiJmYWtlYWxnIiwiZW5jIjoiZmFrZWVuYyJ9".as_bytes()
);
}

#[test]
fn parse_response() {
let data = r#"
Expand Down

0 comments on commit ee031a4

Please sign in to comment.