1 /*
2  * Copyright (c) 2024-2024 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 #include "securec.h"
16 #include "fs_verity_digest.h"
17 #include "signature_tools_log.h"
18 
19 namespace OHOS {
20 namespace SignatureTools {
21 const std::string FsVerityDigest::FSVERITY_DIGEST_MAGIC = "FSVerity";
22 const int FsVerityDigest::DIGEST_HEADER_SIZE = 12;
23 
GetFsVerityDigest(int8_t algoID, std::vector<int8_t>& digest, std::vector<int8_t> &ret)24 void FsVerityDigest::GetFsVerityDigest(int8_t algoID, std::vector<int8_t>& digest,
25                                        std::vector<int8_t> &ret)
26 {
27     const int size = DIGEST_HEADER_SIZE + digest.size();
28     if (size <= 0) {
29         ret = std::vector<int8_t>();
30         return;
31     }
32     std::unique_ptr<ByteBuffer> buffer = std::make_unique<ByteBuffer>(ByteBuffer(size));
33     buffer->PutData(FSVERITY_DIGEST_MAGIC.c_str(), (int32_t)FSVERITY_DIGEST_MAGIC.length());
34     buffer->PutInt16(algoID);
35     buffer->PutInt16((int16_t)digest.size());
36     buffer->PutData(digest.data(), digest.size());
37     buffer->Flip();
38     char dataArr[size];
39     if (memset_s(dataArr, sizeof(dataArr), 0, sizeof(dataArr)) != RET_OK) {
40         SIGNATURE_TOOLS_LOGE("memcpy_s failed");
41         ret = std::vector<int8_t>();
42         return;
43     }
44     buffer->GetData(dataArr, size);
45     ret = std::vector<int8_t>(dataArr, dataArr + size);
46     return;
47 }
48 } // namespace SignatureTools
49 } // namespace OHOS
50