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 "base32_utils.h"
17 
18 namespace OHOS {
19 namespace UDMF {
20 static char BASE32_CHARS[33] = "abcdefghijklmnopqrstuvwxyz234567";
21 
22 static constexpr const uint32_t CHAR_ARRAY_LENGTH = 5;
23 static constexpr const uint32_t ASCII_CHAR_LENGTH = 8;
24 
Encode(const std::string & input)25 std::string Base32::Encode(const std::string &input)
26 {
27     std::string result;
28     uint32_t val = 0;
29     uint32_t valbits = 0;
30     for (char c : input) {
31         val = (val << ASCII_CHAR_LENGTH) + c;
32         valbits += ASCII_CHAR_LENGTH;
33         while (valbits >= CHAR_ARRAY_LENGTH) {
34             valbits -= CHAR_ARRAY_LENGTH;
35             uint32_t index = (val >> valbits) & 0x1f;  // the 31st place.
36             result += BASE32_CHARS[index];
37         }
38     }
39     if (valbits > 0) {
40         val <<= (CHAR_ARRAY_LENGTH - valbits);
41         uint32_t index = val & 0x1f;  // the 31st place.
42         result += BASE32_CHARS[index];
43     }
44     return result;
45 }
46 
Decode(const std::string & input)47 std::string Base32::Decode(const std::string &input)
48 {
49     std::string result;
50     uint32_t val = 0;
51     uint32_t valbits = 0;
52     for (char c : input) {
53         if (c >= 'a' && c <= 'z') {
54             val = (val << CHAR_ARRAY_LENGTH) + (c - 'a');
55             valbits += CHAR_ARRAY_LENGTH;
56         } else if (c >= '2' && c <= '7') {
57             val = (val << CHAR_ARRAY_LENGTH) + (c - '2' + 26); // 26 : a-z
58             valbits += CHAR_ARRAY_LENGTH;
59         }
60         if (valbits >= ASCII_CHAR_LENGTH) {
61             valbits -= ASCII_CHAR_LENGTH;
62             result += static_cast<char>(val >> valbits);
63             val &= (1 << valbits) - 1;
64         }
65     }
66     return result;
67 }
68 
69 } // namespace UDMF
70 } // namespace OHOS
71 
72