-
-
Save rust-play/2e390e9dacaa4c0195dea94663b7c270 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //#![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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment