blob: 49e66e6bc94d3bfbc8d9789cf45949c14b7d2022 [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
17use bssl_ffi::{EVP_MD_size, EVP_sha256, EVP_sha512, EVP_MD};
18
19/// Message digester wrapping `EVP_MD`.
20#[derive(Clone, Debug)]
21pub struct Digester(pub(crate) &'static EVP_MD);
22
23impl Digester {
24 /// Returns a `Digester` implementing `SHA-256` algorithm.
25 pub fn sha256() -> Self {
26 // SAFETY: This function does not access any Rust variables and simply returns
27 // a pointer to the static variable in BoringSSL.
28 let p = unsafe { EVP_sha256() };
29 // SAFETY: The returned pointer should always be valid and points to a static
30 // `EVP_MD`.
31 Self(unsafe { &*p })
32 }
33
34 /// Returns a `Digester` implementing `SHA-512` algorithm.
Alice Wang709cce92023-09-26 10:30:21 +000035 pub fn sha512() -> Self {
36 // SAFETY: This function does not access any Rust variables and simply returns
37 // a pointer to the static variable in BoringSSL.
38 let p = unsafe { EVP_sha512() };
39 // SAFETY: The returned pointer should always be valid and points to a static
40 // `EVP_MD`.
41 Self(unsafe { &*p })
42 }
43
44 /// Returns the digest size in bytes.
45 pub fn size(&self) -> usize {
46 // SAFETY: The inner pointer is fetched from EVP_* hash functions in BoringSSL digest.h
47 unsafe { EVP_MD_size(self.0) }
48 }
49}