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 "scrypt.h"
17 #include <openssl/evp.h>
18 #include <openssl/ossl_typ.h>
19 #include <openssl/kdf.h>
20 #include "iam_logger.h"
21
22 #define LOG_LABEL OHOS::UserIam::Common::LABEL_PIN_AUTH_SDK
23
24 namespace OHOS {
25 namespace UserIam {
26 namespace PinAuth {
27 namespace {
28 constexpr int32_t OUT_LENGTH = 64;
29 constexpr int32_t SCRYPT_N = 32768;
30 constexpr int32_t SCRYPT_R = 8;
31 constexpr int32_t SCRYPT_P = 1;
32 }
33
GetScrypt(const std::vector<uint8_t> data)34 std::vector<uint8_t> Scrypt::GetScrypt(const std::vector<uint8_t> data)
35 {
36 IAM_LOGI("start");
37 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SCRYPT, NULL);
38 if (EVP_PKEY_derive_init(pctx) <= 0) {
39 IAM_LOGE("EVP_PKEY_derive_init fail");
40 return {};
41 }
42 if (EVP_PKEY_CTX_set1_pbe_pass(pctx, data.data(), data.size()) <= 0) {
43 IAM_LOGE("EVP_PKEY_CTX_set1_pbe_pass fail");
44 EVP_PKEY_CTX_free(pctx);
45 return {};
46 }
47 if (EVP_PKEY_CTX_set1_scrypt_salt(pctx, salt_.data(), salt_.size()) <= 0) {
48 IAM_LOGE("EVP_PKEY_CTX_set1_scrypt_salt fail");
49 EVP_PKEY_CTX_free(pctx);
50 return {};
51 }
52 if (EVP_PKEY_CTX_set_scrypt_N(pctx, SCRYPT_N) <= 0) {
53 IAM_LOGE("EVP_PKEY_CTX_set_scrypt_N fail");
54 EVP_PKEY_CTX_free(pctx);
55 return {};
56 }
57 if (EVP_PKEY_CTX_set_scrypt_r(pctx, SCRYPT_R) <= 0) {
58 IAM_LOGE("EVP_PKEY_CTX_set_scrypt_r fail");
59 EVP_PKEY_CTX_free(pctx);
60 return {};
61 }
62 if (EVP_PKEY_CTX_set_scrypt_p(pctx, SCRYPT_P) <= 0) {
63 IAM_LOGE("EVP_PKEY_CTX_set_scrypt_p fail");
64 EVP_PKEY_CTX_free(pctx);
65 return {};
66 }
67
68 std::vector<uint8_t> out(OUT_LENGTH);
69 size_t outlen = out.size();
70 if (EVP_PKEY_derive(pctx, out.data(), &outlen) <= 0) {
71 IAM_LOGE("EVP_PKEY_derive fail");
72 EVP_PKEY_CTX_free(pctx);
73 return {};
74 }
75
76 EVP_PKEY_CTX_free(pctx);
77 return out;
78 }
79 } // namespace PinAuth
80 } // namespace UserIam
81 } // namespace OHOS
82