diff --git a/kbs/src/jwe.rs b/kbs/src/jwe.rs index 44e68d1b1..22b8edd02 100644 --- a/kbs/src/jwe.rs +++ b/kbs/src/jwe.rs @@ -2,7 +2,7 @@ // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 -use aes_gcm::{aead::Aead, Aes256Gcm, KeyInit, Nonce}; +use aes_gcm::{aead::AeadMutInPlace, Aes256Gcm, KeyInit, Nonce}; use anyhow::{anyhow, bail, Context, Result}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use kbs_types::{Response, TeePubKey}; @@ -12,8 +12,9 @@ use serde_json::json; const RSA_ALGORITHM: &str = "RSA1_5"; const AES_GCM_256_ALGORITHM: &str = "A256GCM"; +const AEAD_AAD: &[u8] = b"CoCo"; -pub fn jwe(tee_pub_key: TeePubKey, payload_data: Vec) -> Result { +pub fn jwe(tee_pub_key: TeePubKey, mut payload_data: Vec) -> Result { let TeePubKey::RSA { alg, k_mod, k_exp } = tee_pub_key else { bail!("Only RSA key is support for TEE pub key") }; @@ -25,11 +26,11 @@ pub fn jwe(tee_pub_key: TeePubKey, payload_data: Vec) -> Result { let mut rng = rand::thread_rng(); let aes_sym_key = Aes256Gcm::generate_key(&mut OsRng); - let cipher = Aes256Gcm::new(&aes_sym_key); + let mut cipher = Aes256Gcm::new(&aes_sym_key); let iv = rng.gen::<[u8; 12]>(); let nonce = Nonce::from_slice(&iv); - let encrypted_payload_data = cipher - .encrypt(nonce, payload_data.as_slice()) + let tag = cipher + .encrypt_in_place_detached(nonce, AEAD_AAD, &mut payload_data) .map_err(|e| anyhow!("AES encrypt Resource payload failed: {e}"))?; let k_mod = URL_SAFE_NO_PAD @@ -59,7 +60,7 @@ pub fn jwe(tee_pub_key: TeePubKey, payload_data: Vec) -> Result { .context("serde protected_header failed")?, encrypted_key: URL_SAFE_NO_PAD.encode(wrapped_sym_key), iv: URL_SAFE_NO_PAD.encode(iv), - ciphertext: URL_SAFE_NO_PAD.encode(encrypted_payload_data), - tag: "".to_string(), + ciphertext: URL_SAFE_NO_PAD.encode(payload_data), + tag: URL_SAFE_NO_PAD.encode(tag), }) }