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 "profile_sign_tool.h"
16 #include "signer_factory.h"
17 #include "local_signer.h"
18 #include "localization_adapter.h"
19 #include "file_utils.h"
20 #include "pkcs7_data.h"
21 #include "verify_hap_openssl_utils.h"
22 #include "signature_tools_errno.h"
23
24 namespace OHOS {
25 namespace SignatureTools {
26
GenerateP7b(LocalizationAdapter & adapter,const std::string & content,std::string & ret)27 int ProfileSignTool::GenerateP7b(LocalizationAdapter& adapter, const std::string& content, std::string& ret)
28 {
29 std::unique_ptr<SignerFactory> signerFactory = std::make_unique<SignerFactory>();
30 int result = RET_OK;
31 std::shared_ptr<Signer> signer(signerFactory->GetSigner(adapter));
32 if (signer == NULL) {
33 SIGNATURE_TOOLS_LOGE("signer is NULL, get signer failed");
34 return INVALIDPARAM_ERROR;
35 }
36 const std::string sigAlg = adapter.GetSignAlg();
37 // ret is the generated p7b data
38 result = SignProfile(content, signer, sigAlg, ret);
39 if (result < 0) {
40 SIGNATURE_TOOLS_LOGE("generate p7b failed");
41 return SIGN_ERROR;
42 }
43 PKCS7Data p7Data;
44 result = p7Data.Parse(ret);
45 if (result < 0) {
46 SIGNATURE_TOOLS_LOGE("parse p7b failed");
47 return PARSE_ERROR;
48 }
49 result = p7Data.Verify();
50 if (result < 0) {
51 SIGNATURE_TOOLS_LOGE("verify p7b failed");
52 return VERIFY_ERROR;
53 }
54 return result;
55 }
56 /**
57 * @param content content to sign
58 * @param signer signer
59 * @param sigAlg sign algorithm only SHAwith256 or SHAwith384
60 * @param ret signed data
61 * @return 0:success <0:error
62 */
SignProfile(const std::string & content,const std::shared_ptr<Signer> & signer,const std::string & sigAlg,std::string & ret)63 int ProfileSignTool::SignProfile(const std::string& content, const std::shared_ptr<Signer>& signer,
64 const std::string& sigAlg, std::string& ret)
65 {
66 PKCS7Data p7Data;
67 int result = RET_OK;
68 result = p7Data.Sign(content, signer, sigAlg, ret);
69 if (result < 0) {
70 SIGNATURE_TOOLS_LOGE("SignProfile faild!");
71 return SIGN_ERROR;
72 }
73 return result;
74 }
75 } // namespace SignatureTools
76 } // namespace OHOS