1 /* 2 * Copyright (c) 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 #ifndef AVSESSION_BASE64_UTILS_H 17 #define AVSESSION_BASE64_UTILS_H 18 19 #include <cstring> 20 #include <string> 21 #include <iostream> 22 23 namespace OHOS::AVSession { 24 class Base64Utils { 25 public: Base64Encode(const char * data)26 static std::string Base64Encode(const char *data) 27 { 28 char out[MAX_LENGTH] = {0}; 29 int dataLen = strlen(data); 30 if (dataLen == 0) { 31 out[0] = '\0'; 32 return ""; 33 } 34 35 int index = 0; 36 char c = '\0'; 37 char lastC = '\0'; 38 39 for (int i = 0; i < dataLen; i++) { 40 c = data[i]; 41 switch (i % NUMBER_THREE) { 42 case 0: 43 out[index++] = BASE64_EN[(c >> NUMBER_TWO) & 0x3f]; 44 break; 45 case 1: 46 out[index++] = BASE64_EN[(lastC & 0x3) << NUMBER_FOUR | ((c >> NUMBER_FOUR) & 0xf)]; 47 break; 48 case NUMBER_TWO: 49 out[index++] = BASE64_EN[(lastC & 0xf) << NUMBER_TWO | ((c >> NUMBER_SIX) & 0x3)]; 50 out[index++] = BASE64_EN[c & 0x3f]; 51 break; 52 default: 53 break; 54 } 55 lastC = c; 56 } 57 58 if (dataLen % NUMBER_THREE == NUMBER_ONE) { 59 out[index++] = BASE64_EN[(c & 0x3) << NUMBER_FOUR]; 60 out[index++] = '='; 61 out[index++] = '='; 62 } 63 64 if (dataLen % NUMBER_THREE == NUMBER_TWO) { 65 out[index++] = BASE64_EN[(c & 0xf) << NUMBER_TWO]; 66 out[index++] = '='; 67 } 68 return std::string(out); 69 } 70 71 private: 72 static constexpr const int MAX_LENGTH = 1024; 73 static constexpr const int NUMBER_ONE = 1; 74 static constexpr const int NUMBER_TWO = 2; 75 static constexpr const int NUMBER_THREE = 3; 76 static constexpr const int NUMBER_FOUR = 4; 77 static constexpr const int NUMBER_SIX = 6; 78 static constexpr const char BASE64_EN[] = { 79 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 80 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 81 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 82 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 83 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', 84 '3', '4', '5', '6', '7', '8', '9', '+', '/' 85 }; 86 }; 87 } // namespace OHOS::AVSession 88 89 #endif // AVSESSION_BASE64_UTILS_H 90