# ghash.rs - source
Source of the Rust file `crates/tlsn/src/ghash.rs`.

Skip to main content

#
tlsn/
ghash.rs

    1//! GHASH methods.
    2
    3// This module belongs in tls/core. It was moved out here temporarily.
    4
    5use ghash::{
    6    GHash,
    7    universal_hash::{KeyInit, UniversalHash as UniversalHashReference},
    8};
    9
    10/// Computes a GHASH tag.
    11pub(crate) fn ghash(aad: &[u8], ciphertext: &[u8], key: &[u8; 16]) -> [u8; 16] {
    12    let mut ghash = GHash::new(key.into());
    13    ghash.update_padded(&build_ghash_data(aad.to_vec(), ciphertext.to_owned()));
    14    let out = ghash.finalize();
    15    out.into()
    16}
    17
    18/// Builds padded data for GHASH.
    19pub(crate) fn build_ghash_data(mut aad: Vec<u8>, mut ciphertext: Vec<u8>) -> Vec<u8> {
    20    let associated_data_bitlen = (aad.len() as u64) * 8;
    21    let text_bitlen = (ciphertext.len() as u64) * 8;
    22
    23    let len_block = ((associated_data_bitlen as u128) << 64) + (text_bitlen as u128);
    24
    25    // Pad data to be a multiple of 16 bytes.
    26    let aad_padded_block_count = (aad.len() / 16) + !aad.len().is_multiple_of(16) as usize;
    27    aad.resize(aad_padded_block_count * 16, 0);
    28
    29    let ciphertext_padded_block_count =
    30        (ciphertext.len() / 16) + !ciphertext.len().is_multiple_of(16) as usize;
    31    ciphertext.resize(ciphertext_padded_block_count * 16, 0);
    32
    33    let mut data: Vec<u8> = Vec::with_capacity(aad.len() + ciphertext.len() + 16);
    34    data.extend(aad);
    35    data.extend(ciphertext);
    36    data.extend_from_slice(&len_block.to_be_bytes());
    37
    38    data
    39}