1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
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 
16 #include "hash_calculator.h"
17 
18 namespace OHOS::AVSession {
~HashCalculator()19 HashCalculator::~HashCalculator()
20 {
21     if (context_ != nullptr) {
22         delete context_;
23         context_ = nullptr;
24     }
25 }
26 
Init()27 int32_t HashCalculator::Init()
28 {
29     context_ = new(std::nothrow) SHA256_CTX;
30     if (context_ == nullptr) {
31         return ERR_NO_MEMORY;
32     }
33 
34     if (SHA256_Init(context_) == 0) {
35         SLOGE("sha init failed");
36         return AVSESSION_ERROR;
37     }
38     return AVSESSION_SUCCESS;
39 }
40 
Update(const std::vector<uint8_t> & value)41 int HashCalculator::Update(const std::vector<uint8_t> &value)
42 {
43     if (context_ == nullptr) {
44         return AVSESSION_ERROR;
45     }
46     if (SHA256_Update(context_, value.data(), value.size()) == 0) {
47         SLOGE("update failed");
48         return AVSESSION_ERROR;
49     }
50     return AVSESSION_SUCCESS;
51 }
52 
GetResult(std::vector<uint8_t> & value)53 int HashCalculator::GetResult(std::vector<uint8_t> &value)
54 {
55     if (context_ == nullptr) {
56         return AVSESSION_ERROR;
57     }
58 
59     value.resize(SHA256_DIGEST_LENGTH);
60     if (SHA256_Final(value.data(), context_) == 0) {
61         SLOGE("get result failed");
62         return AVSESSION_ERROR;
63     }
64 
65     return AVSESSION_SUCCESS;
66 }
67 }