在c++中简单实现base编码的加解密
时间: 2024-09-26 20:15:47 浏览: 28
Base编码是一种非二进制的数字系统,它将数字转换成字母组合,常用于数据压缩、存储或加密。在C++中,我们可以使用字符数组来实现Base编码的基本加解密操作。这里我们以常见的Base64为例,因为它是一种常用的Base编码。
**基本实现:**
```cpp
#include <string>
#include <vector>
// Base64表
const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string base64_encode(const std::string& input) {
const size_t padding = static_cast<size_t>(input.size() % 3);
std::vector<char> encoded(input.size() + padding);
size_t i = 0;
for (size_t j = 0; j < input.size(); j += 3) {
encoded[i++] = base64_chars[(input[j] >> 2) & 0x3f];
encoded[i++] = base64_chars[((input[j] << 4) | (input[j + 1] >> 4)) & 0x3f];
encoded[i++] = base64_chars[((input[j + 1] << 2) | (input[j + 2] >> 6)) & 0x3f];
encoded[i++] = base64_chars[input[j + 2] & 0x3f];
}
if (padding == 1) {
encoded[i - 1] = '=';
} else if (padding == 2) {
encoded[i - 2] = encoded[i - 1] = '=';
}
return std::string(encoded.begin(), encoded.end());
}
std::string base64_decode(const std::string& encoded) {
const char* end = encoded.c_str() + encoded.size();
std::vector<uint8_t> decoded;
decoded.reserve(end - encoded.c_str());
for (const char* p = encoded.c_str(); p != end; ++p) {
if (*p == '=') break;
auto index = base64_chars.find(*p);
if (index == base64_chars.npos) continue;
decoded.push_back(index << 2);
if (p + 1 != end) {
index = base64_chars.find(p[1]);
if (index != base64_chars.npos) {
decoded.push_back((index << 4) | ((p[0] & 0x30) >> 4));
}
}
if (p + 2 != end) {
index = base64_chars.find(p[2]);
if (index != base64_chars.npos) {
decoded.push_back(((p[0] & 0xf) << 2) | (index >> 2));
}
}
}
// Handle padding and convert to string
std::string result(decoded.size() * 3 / 4, '\0');
for (size_t i = 0, j = 0; i < decoded.size(); ++i) {
if (decoded[i] != 0) {
result[j++] = static_cast<char>(decoded[i]);
}
}
result.resize(j);
return result;
}
```
阅读全文