1 /*
2 * Copyright (c) 2022-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 #include "cert_manager_crypto_operation.h"
17
18 #include <openssl/evp.h>
19 #include <openssl/rand.h>
20
21 #include "securec.h"
22
23 #include "cm_log.h"
24 #include "cm_type.h"
25
26 #define DIGEST_SHA256_LEN 32
27
CmGetRandom(struct CmBlob * random)28 int32_t CmGetRandom(struct CmBlob *random)
29 {
30 if (CmCheckBlob(random) != CM_SUCCESS) {
31 return CMR_ERROR_INVALID_ARGUMENT;
32 }
33
34 int ret = RAND_bytes(random->data, random->size);
35 if (ret <= 0) {
36 CM_LOG_E("Get random failed");
37 return CMR_ERROR_KEY_OPERATION_FAILED;
38 }
39
40 return CM_SUCCESS;
41 }
42
CmGetHash(const struct CmBlob * inData,struct CmBlob * hash)43 int32_t CmGetHash(const struct CmBlob *inData, struct CmBlob *hash)
44 {
45 if ((CmCheckBlob(inData) != CM_SUCCESS) || (CmCheckBlob(hash) != CM_SUCCESS) ||
46 (hash->size < DIGEST_SHA256_LEN)) {
47 CM_LOG_E("invalid input args");
48 return CMR_ERROR_INVALID_ARGUMENT;
49 }
50
51 const EVP_MD *opensslAlg = EVP_sha256();
52 if (opensslAlg == NULL) {
53 CM_LOG_E("get openssl alg failed");
54 return CMR_ERROR_KEY_OPERATION_FAILED;
55 }
56
57 int32_t ret = EVP_Digest(inData->data, inData->size, hash->data, &hash->size, opensslAlg, NULL);
58 if (ret <= 0) {
59 CM_LOG_E("digest failed");
60 return CMR_ERROR_KEY_OPERATION_FAILED;
61 }
62 return CM_SUCCESS;
63 }
64
65