Skip to content

Instantly share code, notes, and snippets.

@Schniz
Created December 16, 2023 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Schniz/52cbb003309a828149b4a6914d25e4e2 to your computer and use it in GitHub Desktop.
Save Schniz/52cbb003309a828149b4a6914d25e4e2 to your computer and use it in GitHub Desktop.
decrypting a response body
use aes_gcm::{
aead::{generic_array::GenericArray, Aead},
Aes256Gcm,
};
async fn decrypt_body(
mut response: reqwest::Response,
cipher: &Aes256Gcm,
) -> anyhow::Result<reqwest::Response> {
let mut headers = std::mem::take(response.headers_mut());
let status = response.status().as_u16();
let bytes = response.bytes().await?;
let nonce = GenericArray::from_slice(&bytes[..12]);
let decrypted = cipher.decrypt(nonce, &bytes[12..]).unwrap();
let mut response = http::Response::builder().status(status);
let headers_mut = response.headers_mut().unwrap();
for (key, value) in headers.drain() {
if let Some(key) = key {
headers_mut.insert(key, value);
}
}
let response = response.body(decrypted)?;
Ok(reqwest::Response::from(response))
}
#[async_trait::async_trait]
pub trait DecryptBody {
async fn decrypt_body(self, cipher: &Aes256Gcm) -> anyhow::Result<Self>
where
Self: Sized;
}
#[async_trait::async_trait]
impl DecryptBody for reqwest::Response {
async fn decrypt_body(self, cipher: &Aes256Gcm) -> anyhow::Result<Self>
where
Self: Sized,
{
decrypt_body(self, cipher).await
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment