1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "crypto.h"
18
19 extern "C" {
20 #include <string.h>
21
22 #include <openssl/mem.h>
23 #include <openssl/sha.h>
24 } // extern "C"
25
26 namespace nvram {
27 namespace crypto {
28
SHA256(const uint8_t * data,size_t data_size,uint8_t * digest,size_t digest_size)29 void SHA256(const uint8_t* data,
30 size_t data_size,
31 uint8_t* digest,
32 size_t digest_size) {
33 // SHA256 requires an output buffer of at least SHA256_DIGEST_LENGTH.
34 // |digest_size| might be less, so store the digest in a local buffer.
35 uint8_t buffer[SHA256_DIGEST_LENGTH];
36 ::SHA256(data, data_size, buffer);
37
38 // Copy the result to |digest|.
39 if (digest_size < sizeof(buffer)) {
40 memcpy(digest, buffer, digest_size);
41 } else {
42 memcpy(digest, buffer, sizeof(buffer));
43 memset(digest + sizeof(buffer), 0, digest_size - sizeof(buffer));
44 }
45 }
46
47 } // namespace crypto
48 } // namespace nvram
49