Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Last active October 14, 2025 12:45
Show Gist options
  • Select an option

  • Save RandyMcMillan/f53124e00792b9e1b63fba5e912f5450 to your computer and use it in GitHub Desktop.

Select an option

Save RandyMcMillan/f53124e00792b9e1b63fba5e912f5450 to your computer and use it in GitHub Desktop.
faux_hmac.rs
//#![no_std]
fn sha256_placeholder(data: &[u8]) -> [u8; 32] {
let mut hash = [0u8; 32];
let len_bytes = (data.len() as u32).to_le_bytes();
hash[0..4].copy_from_slice(&len_bytes);
hash
}
const SHA256_BLOCK_SIZE: usize = 64;
const SHA256_OUTPUT_SIZE: usize = 32;
fn hmac_sha256_std_only(key: &[u8], message: &[u8]) -> [u8; SHA256_OUTPUT_SIZE] {
let mut key_padded: Vec<u8> = key.to_vec();
if key_padded.len() > SHA256_BLOCK_SIZE {
let hashed_key = sha256_placeholder(&key_padded);
key_padded = hashed_key.to_vec();
}
key_padded.resize(SHA256_BLOCK_SIZE, 0x00);
let ipad: [u8; SHA256_BLOCK_SIZE] = [0x36; SHA256_BLOCK_SIZE];
let mut inner_key_pad = key_padded.clone();
for (i, &k_byte) in key_padded.iter().enumerate() {
inner_key_pad[i] = k_byte ^ ipad[i];
}
let mut inner_hash_input = inner_key_pad;
inner_hash_input.extend_from_slice(message);
let inner_hash = sha256_placeholder(&inner_hash_input);
let opad: [u8; SHA256_BLOCK_SIZE] = [0x5c; SHA256_BLOCK_SIZE];
let mut outer_key_pad = key_padded.clone();
for (i, &k_byte) in key_padded.iter().enumerate() {
outer_key_pad[i] = k_byte ^ opad[i];
}
let mut outer_hash_input = outer_key_pad;
outer_hash_input.extend_from_slice(&inner_hash);
sha256_placeholder(&outer_hash_input)
}
fn main() {
let key = b"my_secret_key";
let message = b"The data to be authenticated by HMAC.";
let hmac_result = hmac_sha256_std_only(key, message);
let _ = hmac_result;
}
@RandyMcMillan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment