blob: 6c65d7f02079a6a131216a0c1ede4e816e470d6c [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};
19use bssl_ffi::SHA256;
20
21/// The length of a SHA256 digest.
22pub(crate) const SHA256_DIGEST_LENGTH: usize = bssl_ffi::SHA256_DIGEST_LENGTH as usize;
23
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}