blob: 8b8905c96b3b1bae27009cfb8194db2c3566a43c [file] [log] [blame]
Victor Hsiehd1cb0d72020-11-06 13:49:55 -08001/*
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
Victor Hsiehd1cb0d72020-11-06 13:49:55 -080017use std::mem::MaybeUninit;
18
19use thiserror::Error;
20
21#[derive(Error, Debug)]
22pub enum CryptoError {
23 #[error("Unexpected error returned from {0}")]
24 Unexpected(&'static str),
25}
26
27use authfs_crypto_bindgen::{SHA256_Final, SHA256_Init, SHA256_Update, SHA256_CTX};
28
29pub struct Sha256Hasher {
30 ctx: SHA256_CTX,
31}
32
33impl Sha256Hasher {
34 pub const HASH_SIZE: usize = 32;
35
36 pub fn new() -> Result<Sha256Hasher, CryptoError> {
37 // Safe assuming the crypto FFI should initialize the uninitialized `ctx`, which is
38 // currently a pure data struct.
39 unsafe {
40 let mut ctx = MaybeUninit::uninit();
41 if SHA256_Init(ctx.as_mut_ptr()) == 0 {
42 Err(CryptoError::Unexpected("SHA256_Init"))
43 } else {
44 Ok(Sha256Hasher { ctx: ctx.assume_init() })
45 }
46 }
47 }
48
49 pub fn update(&mut self, data: &[u8]) -> Result<&mut Self, CryptoError> {
50 // Safe assuming the crypto FFI will not touch beyond `ctx` as pure data.
51 let retval = unsafe {
52 SHA256_Update(&mut self.ctx, data.as_ptr() as *mut std::ffi::c_void, data.len())
53 };
54 if retval == 0 {
55 Err(CryptoError::Unexpected("SHA256_Update"))
56 } else {
57 Ok(self)
58 }
59 }
60
61 pub fn finalize(&mut self) -> Result<[u8; Self::HASH_SIZE], CryptoError> {
62 let mut md = [0u8; Self::HASH_SIZE];
63 // Safe assuming the crypto FFI will not touch beyond `ctx` as pure data.
64 let retval = unsafe { SHA256_Final(md.as_mut_ptr(), &mut self.ctx) };
65 if retval == 0 {
66 Err(CryptoError::Unexpected("SHA256_Final"))
67 } else {
68 Ok(md)
69 }
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76
77 fn to_hex_string(data: &[u8]) -> String {
78 data.iter().map(|&b| format!("{:02x}", b)).collect()
79 }
80
81 #[test]
82 fn verify_hash_values() -> Result<(), CryptoError> {
83 let hash = Sha256Hasher::new()?.update(&[0; 0])?.finalize()?;
84 let s: String = to_hex_string(&hash);
85 assert_eq!(s, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
86
87 let hash = Sha256Hasher::new()?
88 .update(&[1u8; 1])?
89 .update(&[2u8; 1])?
90 .update(&[3u8; 1])?
91 .finalize()?;
92 let s: String = to_hex_string(&hash);
93 assert_eq!(s, "039058c6f2c0cb492c533b0a4d14ef77cc0f78abccced5287d84a1a2011cfb81");
94 Ok(())
95 }
96}