• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 = size / 3 * 4 + (size % 3 == 0 ? 0 : 4) + 1;
27     std::vector<unsigned char> outBuffer(bufLen, 0);
28     auto outLen = EVP_EncodeBlock(outBuffer.data(), input.data(), size);
29     if (outLen < 0) {
30         return nullptr;
31     }
32     outBuffer.resize(outLen);
33     return std::make_shared<std::string>(outBuffer.begin(), outBuffer.end());
34 }
Decode(const std::string & input)35 std::shared_ptr<std::vector<unsigned char>> Base64::Decode(const std::string &input)
36 {
37     auto size = input.size();
38     size_t bufLen = size / 4 * 3;
39     auto outBuffer = std::make_shared<std::vector<unsigned char>>(bufLen, 0);
40     auto outLen = EVP_DecodeBlock(reinterpret_cast<unsigned char *>(outBuffer->data()),
41                                   reinterpret_cast<const unsigned char *>(input.c_str()), size);
42     if (outLen < 0) {
43         return nullptr;
44     }
45     for (unsigned int i = 0; i < MAX_BASE64_BUF_PADDING_SIZE; ++i) {
46         if (size > 1 + i && input.at(size - 1 - i) == '=') {
47             outLen--;
48         } else {
49             break;
50         }
51     }
52 
53     outBuffer->resize(outLen);
54     return outBuffer;
55 }
56 }
57 }