blob: 47e4abae1ce09e0826386ac125cb8f8531499bfc [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.
35 #[allow(dead_code)]
36 pub fn sha512() -> 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_sha512() };
40 // SAFETY: The returned pointer should always be valid and points to a static
41 // `EVP_MD`.
42 Self(unsafe { &*p })
43 }
44
45 /// Returns the digest size in bytes.
46 pub fn size(&self) -> usize {
47 // SAFETY: The inner pointer is fetched from EVP_* hash functions in BoringSSL digest.h
48 unsafe { EVP_MD_size(self.0) }
49 }
50}