blob: 66b4a7cad310b9d6845fff48116676b121e35b54 [file] [log] [blame]
Alice Wang0271ee02023-11-15 15:03:42 +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 SHA functions in BoringSSL sha.h.
16
17use crate::util::to_call_failed_error;
18use bssl_avf_error::{ApiName, Result};
Maurice Lam0322b8c2023-12-18 22:13:48 +000019use bssl_sys::SHA256;
Alice Wang0271ee02023-11-15 15:03:42 +000020
21/// The length of a SHA256 digest.
Maurice Lam0322b8c2023-12-18 22:13:48 +000022pub(crate) const SHA256_DIGEST_LENGTH: usize = bssl_sys::SHA256_DIGEST_LENGTH as usize;
Alice Wang0271ee02023-11-15 15:03:42 +000023
24/// Computes the SHA256 digest of the provided `data``.
25pub fn sha256(data: &[u8]) -> Result<[u8; SHA256_DIGEST_LENGTH]> {
26 let mut out = [0u8; SHA256_DIGEST_LENGTH];
27 // SAFETY: This function reads `data` and writes to `out` within its bounds.
28 // `out` has `SHA256_DIGEST_LENGTH` bytes of space for write.
29 let ret = unsafe { SHA256(data.as_ptr(), data.len(), out.as_mut_ptr()) };
30 if ret.is_null() {
31 Err(to_call_failed_error(ApiName::SHA256))
32 } else {
33 Ok(out)
34 }
35}