1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 use std::mem::MaybeUninit; 18 19 use thiserror::Error; 20 21 #[derive(Error, Debug)] 22 pub enum CryptoError { 23 #[error("Unexpected error returned from {0}")] 24 Unexpected(&'static str), 25 } 26 27 use authfs_crypto_bindgen::{SHA256_Final, SHA256_Init, SHA256_Update, SHA256_CTX}; 28 29 pub type Sha256Hash = [u8; Sha256Hasher::HASH_SIZE]; 30 31 pub struct Sha256Hasher { 32 ctx: SHA256_CTX, 33 } 34 35 impl Sha256Hasher { 36 pub const HASH_SIZE: usize = 32; 37 38 pub const HASH_OF_4096_ZEROS: [u8; Self::HASH_SIZE] = [ 39 0xad, 0x7f, 0xac, 0xb2, 0x58, 0x6f, 0xc6, 0xe9, 0x66, 0xc0, 0x04, 0xd7, 0xd1, 0xd1, 0x6b, 40 0x02, 0x4f, 0x58, 0x05, 0xff, 0x7c, 0xb4, 0x7c, 0x7a, 0x85, 0xda, 0xbd, 0x8b, 0x48, 0x89, 41 0x2c, 0xa7, 42 ]; 43 44 pub fn new() -> Result<Sha256Hasher, CryptoError> { 45 // Safe assuming the crypto FFI should initialize the uninitialized `ctx`, which is 46 // currently a pure data struct. 47 unsafe { 48 let mut ctx = MaybeUninit::uninit(); 49 if SHA256_Init(ctx.as_mut_ptr()) == 0 { 50 Err(CryptoError::Unexpected("SHA256_Init")) 51 } else { 52 Ok(Sha256Hasher { ctx: ctx.assume_init() }) 53 } 54 } 55 } 56 57 pub fn update(&mut self, data: &[u8]) -> Result<&mut Self, CryptoError> { 58 // Safe assuming the crypto FFI will not touch beyond `ctx` as pure data. 59 let retval = unsafe { 60 SHA256_Update(&mut self.ctx, data.as_ptr() as *mut std::ffi::c_void, data.len()) 61 }; 62 if retval == 0 { 63 Err(CryptoError::Unexpected("SHA256_Update")) 64 } else { 65 Ok(self) 66 } 67 } 68 69 pub fn update_from<I, T>(&mut self, iter: I) -> Result<&mut Self, CryptoError> 70 where 71 I: IntoIterator<Item = T>, 72 T: AsRef<[u8]>, 73 { 74 for data in iter { 75 self.update(data.as_ref())?; 76 } 77 Ok(self) 78 } 79 80 pub fn finalize(&mut self) -> Result<[u8; Self::HASH_SIZE], CryptoError> { 81 let mut md = [0u8; Self::HASH_SIZE]; 82 // Safe assuming the crypto FFI will not touch beyond `ctx` as pure data. 83 let retval = unsafe { SHA256_Final(md.as_mut_ptr(), &mut self.ctx) }; 84 if retval == 0 { 85 Err(CryptoError::Unexpected("SHA256_Final")) 86 } else { 87 Ok(md) 88 } 89 } 90 } 91 92 #[cfg(test)] 93 mod tests { 94 use super::*; 95 96 fn to_hex_string(data: &[u8]) -> String { 97 data.iter().map(|&b| format!("{:02x}", b)).collect() 98 } 99 100 #[test] 101 fn verify_hash_values() -> Result<(), CryptoError> { 102 let hash = Sha256Hasher::new()?.update(&[0; 0])?.finalize()?; 103 let s: String = to_hex_string(&hash); 104 assert_eq!(s, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); 105 106 let hash = Sha256Hasher::new()? 107 .update(&[1u8; 1])? 108 .update(&[2u8; 1])? 109 .update(&[3u8; 1])? 110 .finalize()?; 111 let s: String = to_hex_string(&hash); 112 assert_eq!(s, "039058c6f2c0cb492c533b0a4d14ef77cc0f78abccced5287d84a1a2011cfb81"); 113 Ok(()) 114 } 115 116 #[test] 117 fn sha256_of_4096_zeros() -> Result<(), CryptoError> { 118 let hash = Sha256Hasher::new()?.update(&[0u8; 4096])?.finalize()?; 119 assert_eq!(hash, Sha256Hasher::HASH_OF_4096_ZEROS); 120 Ok(()) 121 } 122 } 123