1 /* 2 * Copyright (c) 2023 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 #ifndef OHOS_LOCAL_SIGN_KEY_H 17 #define OHOS_LOCAL_SIGN_KEY_H 18 19 #include <memory> 20 #include <string> 21 22 #include "byte_buffer.h" 23 #include "errcode.h" 24 #include "hks_type.h" 25 #include "hks_api.h" 26 #include "hks_param.h" 27 #include "log.h" 28 #include "sign_key.h" 29 30 namespace OHOS { 31 namespace Security { 32 namespace CodeSign { 33 class LocalSignKey : public SignKey { 34 public: 35 static LocalSignKey &GetInstance(); 36 const ByteBuffer *GetSignCert() override; 37 bool Sign(const ByteBuffer &data, ByteBuffer &ret) override; 38 const HksCertChain *GetCertChain(); 39 bool InitKey(); 40 private: 41 class HUKSParamSet { 42 public: HUKSParamSet()43 HUKSParamSet() : paramSet(nullptr) 44 { 45 } 46 Init(const struct HksParam tmpParams[],uint32_t paramCount)47 bool Init(const struct HksParam tmpParams[], uint32_t paramCount) 48 { 49 int32_t ret = HksInitParamSet(¶mSet); 50 if (ret != HKS_SUCCESS) { 51 LOG_ERROR(LABEL, "HksInitParamSet failed"); 52 return false; 53 } 54 ret = HksAddParams(paramSet, tmpParams, paramCount); 55 if (ret != HKS_SUCCESS) { 56 LOG_ERROR(LABEL, "HksAddParams failed"); 57 return false; 58 } 59 60 ret = HksBuildParamSet(¶mSet); 61 if (ret != HKS_SUCCESS) { 62 LOG_ERROR(LABEL, "HksBuildParamSet failed"); 63 return false; 64 } 65 return true; 66 } 67 GetParamSet()68 HksParamSet *GetParamSet() const 69 { 70 return paramSet; 71 } 72 ~HUKSParamSet()73 ~HUKSParamSet() 74 { 75 if (paramSet != nullptr) { 76 HksFreeParamSet(¶mSet); 77 paramSet = nullptr; 78 } 79 } 80 private: 81 HksParamSet *paramSet = nullptr; 82 }; 83 84 LocalSignKey(); 85 ~LocalSignKey(); 86 87 LocalSignKey(const LocalSignKey &source) = delete; 88 LocalSignKey &operator = (const LocalSignKey &source) = delete; 89 90 bool GenerateKey(); 91 HksCertChain *QueryCertChain(); 92 bool GetKeyParamSet(HUKSParamSet ¶mSet); 93 bool GetAttestParamSet(HUKSParamSet ¶mSet); 94 bool GetSignParamSet(HUKSParamSet ¶mSet); 95 bool SignByHUKS(const struct HksBlob *inData, struct HksBlob *outData); 96 97 private: 98 ByteBuffer *cert_ = nullptr; 99 HksCertChain *certChain_ = nullptr; 100 std::unique_ptr<uint8_t[]> challenge_ = nullptr; 101 std::string algorithm_ = "ECDSA256"; 102 }; 103 } 104 } 105 } 106 107 #endif