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 #include <vector> 23 24 namespace OHOS::AVSession { 25 class Base64Utils { 26 static constexpr int NUMBER_ZERO = 0; 27 static constexpr int NUMBER_ONE = 1; 28 static constexpr int NUMBER_TWO = 2; 29 static constexpr int NUMBER_THREE = 3; 30 static constexpr int NUMBER_FOUR = 4; 31 static constexpr int NUMBER_SIX = 6; 32 33 public: Base64Encode(const std::vector<uint8_t> & data)34 static std::string Base64Encode(const std::vector<uint8_t>& data) 35 { 36 std::string encoded; 37 int i = 0; 38 uint8_t byte3[NUMBER_THREE] = {0}; 39 uint8_t byte4[NUMBER_FOUR] = {0}; 40 for (uint8_t byte : data) { 41 byte3[i++] = byte; 42 if (i == NUMBER_THREE) { 43 byte4[NUMBER_ZERO] = (byte3[NUMBER_ZERO] & 0xfc) >> NUMBER_TWO; 44 byte4[NUMBER_ONE] = ((byte3[NUMBER_ZERO] & 0x03) << NUMBER_FOUR) | 45 ((byte3[NUMBER_ONE] & 0xf0) >> NUMBER_FOUR); 46 byte4[NUMBER_TWO] = ((byte3[NUMBER_ONE] & 0x0f) << NUMBER_TWO) | 47 ((byte3[NUMBER_TWO] & 0xc0) >> NUMBER_SIX); 48 byte4[NUMBER_THREE] = byte3[NUMBER_TWO] & 0x3f; 49 for (i = 0; i < NUMBER_FOUR; i++) { 50 encoded += kBase64Chars[byte4[i]]; 51 } 52 i = NUMBER_ZERO; 53 } 54 } 55 if (i != NUMBER_ZERO) { 56 for (int k = i; k < NUMBER_THREE; k++) { 57 byte3[k] = NUMBER_ZERO; 58 } 59 byte4[NUMBER_ZERO] = (byte3[NUMBER_ZERO] & 0xfc) >> NUMBER_TWO; 60 byte4[NUMBER_ONE] = ((byte3[NUMBER_ZERO] & 0x03) << NUMBER_FOUR) | 61 ((byte3[NUMBER_ONE] & 0xf0) >> NUMBER_FOUR); 62 byte4[NUMBER_TWO] = ((byte3[NUMBER_ONE] & 0x0f) << NUMBER_TWO) | 63 ((byte3[NUMBER_TWO] & 0xc0) >> NUMBER_SIX); 64 for (int k = 0; k < i + NUMBER_ONE; k++) { 65 encoded += kBase64Chars[byte4[k]]; 66 } 67 while (i++ < NUMBER_THREE) { 68 encoded += '='; 69 } 70 } 71 return encoded; 72 } 73 74 private: 75 static const std::string kBase64Chars; 76 }; 77 const std::string Base64Utils::kBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 78 "abcdefghijklmnopqrstuvwxyz" 79 "0123456789+/"; 80 } // namespace OHOS::AVSession 81 82 #endif // AVSESSION_BASE64_UTILS_H 83