1 /*
2 * Copyright (c) 2021 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 "app_rsa.h"
17
18 #include <mbedtls/entropy.h>
19
20 #include "ohos_types.h"
21
AppRsaInit(AppRsaContext * rsa)22 void AppRsaInit(AppRsaContext *rsa)
23 {
24 if (rsa == NULL) {
25 return;
26 }
27 mbedtls_pk_init(&rsa->context);
28 return;
29 }
30
AppRsaDecodePublicKey(AppRsaContext * rsa,const uint8 * publicKey,uint32 length)31 int32 AppRsaDecodePublicKey(AppRsaContext *rsa, const uint8 *publicKey, uint32 length)
32 {
33 if ((rsa == NULL) || (publicKey == NULL)) {
34 return OHOS_FAILURE;
35 }
36
37 int32 parseRet = mbedtls_pk_parse_public_key(&rsa->context, publicKey, length);
38 if (parseRet != RSA_SUCCESS) {
39 return OHOS_FAILURE;
40 }
41
42 return OHOS_SUCCESS;
43 }
44
AppVerifyData(AppRsaContext * rsa,const uint8 * plainBuf,uint32 plainBufLen,const uint8 * cipherBuf,uint32 cipherBufLen)45 int32 AppVerifyData(AppRsaContext *rsa, const uint8 *plainBuf, uint32 plainBufLen, const uint8 *cipherBuf,
46 uint32 cipherBufLen)
47 {
48 int32 ret;
49
50 if ((rsa == NULL) || (plainBuf == NULL) || (cipherBuf == NULL) || (plainBufLen == 0) || (cipherBufLen == 0)) {
51 printf("input error.\r\n");
52 return OHOS_FAILURE;
53 }
54
55 if (!mbedtls_pk_can_do(&(rsa->context), MBEDTLS_PK_RSA)) {
56 printf(" failed\n ! Key is not an RSA key\n");
57 return OHOS_FAILURE;
58 }
59 mbedtls_entropy_context entropy;
60 mbedtls_rsa_set_padding(mbedtls_pk_rsa(rsa->context), MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA256);
61 mbedtls_entropy_init(&entropy);
62 ret = mbedtls_rsa_pkcs1_verify(mbedtls_pk_rsa(rsa->context), MBEDTLS_MD_SHA256, plainBufLen, plainBuf, cipherBuf);
63 if (ret != 0) {
64 printf("sign failed. %x\r\n", -ret);
65 return OHOS_FAILURE;
66 }
67
68 return OHOS_SUCCESS;
69 }
70
AppRsaFree(AppRsaContext * rsa)71 void AppRsaFree(AppRsaContext *rsa)
72 {
73 if (rsa == NULL) {
74 return;
75 }
76
77 mbedtls_pk_free(&rsa->context);
78 return;
79 }
80