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 "base64.h"
17
18 #include "openssl/evp.h"
19
20 namespace OHOS {
21 namespace Telephony {
22 constexpr unsigned int MAX_BASE64_BUF_PADDING_SIZE = 2;
Encode(const std::vector<unsigned char> & input)23 std::shared_ptr<std::string> Base64::Encode(const std::vector<unsigned char> &input)
24 {
25 auto size = input.size();
26 size_t bufLen = BASE64_ENCODED_UNIT * ((size + BASE64_INPUT_UNIT_PAD) / BASE64_INPUT_UNIT) +
27 BASE64_OUTPUT_PADDING;
28 std::vector<unsigned char> outBuffer(bufLen, 0);
29 auto outLen = EVP_EncodeBlock(outBuffer.data(), input.data(), size);
30 if (outLen < 0) {
31 return nullptr;
32 }
33 outBuffer.resize(outLen);
34 return std::make_shared<std::string>(outBuffer.begin(), outBuffer.end());
35 }
36
Encode(const std::string & input)37 std::shared_ptr<std::string> Base64::Encode(const std::string &input)
38 {
39 size_t inputSize = input.size();
40 size_t encodeSize = BASE64_ENCODED_UNIT * ((inputSize + BASE64_INPUT_UNIT_PAD) / BASE64_INPUT_UNIT) +
41 BASE64_OUTPUT_PADDING;
42 auto outStr = std::make_shared<std::string>(encodeSize, '\0');
43 auto inputPtr = reinterpret_cast<const unsigned char*>(input.data());
44 auto outStrPtr = reinterpret_cast<unsigned char*>(outStr->data());
45
46 int actualSize = EVP_EncodeBlock(outStrPtr, inputPtr, static_cast<int>(inputSize));
47 if (actualSize < 0) {
48 return nullptr;
49 }
50 outStr->resize(actualSize);
51 return outStr;
52 }
53
Decode(const std::string & input)54 std::shared_ptr<std::vector<unsigned char>> Base64::Decode(const std::string &input)
55 {
56 auto size = input.size();
57 size_t bufLen = size / BASE64_ENCODED_UNIT * BASE64_INPUT_UNIT;
58 auto outBuffer = std::make_shared<std::vector<unsigned char>>(bufLen, 0);
59 auto outLen = EVP_DecodeBlock(reinterpret_cast<unsigned char *>(outBuffer->data()),
60 reinterpret_cast<const unsigned char *>(input.c_str()), size);
61 if (outLen < 0) {
62 return nullptr;
63 }
64 for (unsigned int i = 0; i < MAX_BASE64_BUF_PADDING_SIZE; ++i) {
65 if (size > 1 + i && input.at(size - 1 - i) == '=') {
66 outLen--;
67 } else {
68 break;
69 }
70 }
71
72 outBuffer->resize(outLen);
73 return outBuffer;
74 }
75 }
76 }