1/*
2 * Copyright (C) 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
16#include "crypto_digest.h"
17#include "md.h"
18#include "crypto_common.h"
19#include "blob.h"
20#include "object_base.h"
21#include "result.h"
22#include "native_common.h"
23
24struct OH_CryptoDigest {
25    HcfObjectBase base;
26
27    HcfResult (*update)(HcfMd *self, HcfBlob *input);
28
29    HcfResult (*doFinal)(HcfMd *self, HcfBlob *output);
30
31    uint32_t (*getMdLength)(HcfMd *self);
32
33    const char *(*getAlgoName)(HcfMd *self);
34};
35
36OH_Crypto_ErrCode OH_CryptoDigest_Create(const char *algoName, OH_CryptoDigest **ctx)
37{
38    if (ctx == NULL) {
39        return CRYPTO_INVALID_PARAMS;
40    }
41    HcfResult ret = HcfMdCreate(algoName, (HcfMd **)ctx);
42    return GetOhCryptoErrCode(ret);
43}
44
45OH_Crypto_ErrCode OH_CryptoDigest_Update(OH_CryptoDigest *ctx, Crypto_DataBlob *in)
46{
47    if ((ctx == NULL) || (ctx->update == NULL) || (in == NULL)) {
48        return CRYPTO_INVALID_PARAMS;
49    }
50    HcfResult ret = ctx->update((HcfMd *)ctx, (HcfBlob *)in);
51    return GetOhCryptoErrCode(ret);
52}
53
54OH_Crypto_ErrCode OH_CryptoDigest_Final(OH_CryptoDigest *ctx, Crypto_DataBlob *out)
55{
56    if ((ctx == NULL) || (ctx->doFinal == NULL) || (out == NULL)) {
57        return CRYPTO_INVALID_PARAMS;
58    }
59    HcfResult ret = ctx->doFinal((HcfMd *)ctx, (HcfBlob *)out);
60    return GetOhCryptoErrCode(ret);
61}
62
63uint32_t OH_CryptoDigest_GetLength(OH_CryptoDigest *ctx)
64{
65    if ((ctx == NULL) || (ctx->getMdLength == NULL)) {
66        return CRYPTO_INVALID_PARAMS;
67    }
68    return ctx->getMdLength((HcfMd *)ctx);
69}
70
71const char *OH_CryptoDigest_GetAlgoName(OH_CryptoDigest *ctx)
72{
73    if ((ctx == NULL) || (ctx->getAlgoName == NULL)) {
74        return NULL;
75    }
76    return ctx->getAlgoName((HcfMd *)ctx);
77}
78
79void OH_DigestCrypto_Destroy(OH_CryptoDigest *ctx)
80{
81    if ((ctx == NULL) || (ctx->base.destroy == NULL)) {
82        return;
83    }
84    ctx->base.destroy((HcfObjectBase *)ctx);
85}