blob: e986a387dea720891de94f8d3fd3223b554eced1 [file] [log] [blame]
Alice Wang709cce92023-09-26 10:30:21 +00001// Copyright 2023, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Wrappers of the digest functions in BoringSSL digest.h.
16
Alice Wang884648d2023-12-01 09:50:20 +000017use crate::util::{check_int_result, to_call_failed_error};
18use alloc::vec;
19use alloc::vec::Vec;
20use bssl_avf_error::{ApiName, Error, Result};
Alice Wang7468ae42023-11-30 10:20:36 +000021use bssl_ffi::{
Alice Wang884648d2023-12-01 09:50:20 +000022 EVP_Digest, EVP_MD_CTX_free, EVP_MD_CTX_new, EVP_MD_size, EVP_sha256, EVP_sha384, EVP_sha512,
23 EVP_MAX_MD_SIZE, EVP_MD, EVP_MD_CTX,
Alice Wang7468ae42023-11-30 10:20:36 +000024};
Alice Wang884648d2023-12-01 09:50:20 +000025use core::ptr::{self, NonNull};
26use log::error;
27
28const MAX_DIGEST_SIZE: usize = EVP_MAX_MD_SIZE as usize;
Alice Wang709cce92023-09-26 10:30:21 +000029
30/// Message digester wrapping `EVP_MD`.
31#[derive(Clone, Debug)]
32pub struct Digester(pub(crate) &'static EVP_MD);
33
34impl Digester {
35 /// Returns a `Digester` implementing `SHA-256` algorithm.
36 pub fn sha256() -> Self {
37 // SAFETY: This function does not access any Rust variables and simply returns
38 // a pointer to the static variable in BoringSSL.
39 let p = unsafe { EVP_sha256() };
40 // SAFETY: The returned pointer should always be valid and points to a static
41 // `EVP_MD`.
Alice Wang884648d2023-12-01 09:50:20 +000042 Self(unsafe { p.as_ref().unwrap() })
43 }
44
45 /// Returns a `Digester` implementing `SHA-384` algorithm.
46 pub fn sha384() -> Self {
47 // SAFETY: This function does not access any Rust variables and simply returns
48 // a pointer to the static variable in BoringSSL.
49 let p = unsafe { EVP_sha384() };
50 // SAFETY: The returned pointer should always be valid and points to a static
51 // `EVP_MD`.
52 Self(unsafe { p.as_ref().unwrap() })
Alice Wang709cce92023-09-26 10:30:21 +000053 }
54
55 /// Returns a `Digester` implementing `SHA-512` algorithm.
Alice Wang709cce92023-09-26 10:30:21 +000056 pub fn sha512() -> Self {
57 // SAFETY: This function does not access any Rust variables and simply returns
58 // a pointer to the static variable in BoringSSL.
59 let p = unsafe { EVP_sha512() };
60 // SAFETY: The returned pointer should always be valid and points to a static
61 // `EVP_MD`.
Alice Wang884648d2023-12-01 09:50:20 +000062 Self(unsafe { p.as_ref().unwrap() })
Alice Wang709cce92023-09-26 10:30:21 +000063 }
64
65 /// Returns the digest size in bytes.
66 pub fn size(&self) -> usize {
67 // SAFETY: The inner pointer is fetched from EVP_* hash functions in BoringSSL digest.h
68 unsafe { EVP_MD_size(self.0) }
69 }
Alice Wang884648d2023-12-01 09:50:20 +000070
71 /// Computes the digest of the provided `data`.
72 pub fn digest(&self, data: &[u8]) -> Result<Vec<u8>> {
73 let mut out = vec![0u8; MAX_DIGEST_SIZE];
74 let mut out_size = 0;
75 let engine = ptr::null_mut(); // Use the default engine.
76 let ret =
77 // SAFETY: This function reads `data` and writes to `out` within its bounds.
78 // `out` has `MAX_DIGEST_SIZE` bytes of space for write as required in the
79 // BoringSSL spec.
80 // The digester is a valid pointer to a static `EVP_MD` as it is returned by
81 // BoringSSL API during the construction of this struct.
82 unsafe {
83 EVP_Digest(
84 data.as_ptr() as *const _,
85 data.len(),
86 out.as_mut_ptr(),
87 &mut out_size,
88 self.0,
89 engine,
90 )
91 };
92 check_int_result(ret, ApiName::EVP_Digest)?;
93 let out_size = usize::try_from(out_size).map_err(|e| {
94 error!("Failed to convert digest size to usize: {:?}", e);
95 Error::InternalError
96 })?;
97 if self.size() != out_size {
98 return Err(to_call_failed_error(ApiName::EVP_Digest));
99 }
100 out.truncate(out_size);
101 Ok(out)
102 }
Alice Wang709cce92023-09-26 10:30:21 +0000103}
Alice Wang7468ae42023-11-30 10:20:36 +0000104
105/// Message digester context wrapping `EVP_MD_CTX`.
106#[derive(Clone, Debug)]
107pub struct DigesterContext(NonNull<EVP_MD_CTX>);
108
109impl Drop for DigesterContext {
110 fn drop(&mut self) {
111 // SAFETY: This function frees any resources owned by `EVP_MD_CTX` and resets it to a
112 // freshly initialised state and then frees the context.
113 // It is safe because `EVP_MD_CTX` has been allocated by BoringSSL and isn't used after
114 // this.
115 unsafe { EVP_MD_CTX_free(self.0.as_ptr()) }
116 }
117}
118
119impl DigesterContext {
120 /// Creates a new `DigesterContext` wrapping a freshly allocated and initialised `EVP_MD_CTX`.
121 pub fn new() -> Result<Self> {
122 // SAFETY: The returned pointer is checked below.
123 let ctx = unsafe { EVP_MD_CTX_new() };
124 NonNull::new(ctx).map(Self).ok_or(to_call_failed_error(ApiName::EVP_MD_CTX_new))
125 }
126
127 pub(crate) fn as_mut_ptr(&mut self) -> *mut EVP_MD_CTX {
128 self.0.as_ptr()
129 }
130}