Base64编码是一种将二进制数据转换为ASCII字符串的方法,主要用于在文本协议(如HTTP、SMTP等)中传输二进制数据
<iostream>
和<string>
头文件。#include<iostream>
#include<string>
std::string base64_encode(const std::string& input) {
const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string encoded;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
for (unsigned int i = 0; i< input.size(); i++) {
char_array_3[i % 3] = input[i];
if ((i + 1) % 3 == 0) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (int j = 0; j < 4; j++) {
encoded += base64_chars[char_array_4[j]];
}
}
}
if (i % 3 != 0) {
for (int j = i % 3; j < 3; j++) {
char_array_3[j] = '\0';
}
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (int j = 0; j < (i % 3) + 1; j++) {
encoded += base64_chars[char_array_4[j]];
}
while (i % 3 != 0) {
encoded += '=';
i++;
}
}
return encoded;
}
std::string base64_decode(const std::string& encoded) {
const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string decoded;
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
for (unsigned int i = 0; i< encoded.size(); i++) {
if (encoded[i] == '=') {
break;
}
in_ = base64_chars.find(encoded[i]);
if (in_ == -1) {
throw std::runtime_error("Invalid Base64 character");
}
char_array_4[i % 4] = in_;
if ((i + 1) % 4 == 0) {
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (int j = 0; j < 3; j++) {
decoded += char_array_3[j];
}
}
}
if (i % 4 != 0) {
for (int j = i % 4; j < 4; j++) {
char_array_4[j] = 0;
}
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (int j = 0; j < (i % 4) - 1; j++) {
decoded += char_array_3[j];
}
}
return decoded;
}
int main() {
std::string input = "Hello, World!";
std::string encoded = base64_encode(input);
std::string decoded = base64_decode(encoded);
std::cout << "Input: "<< input<< std::endl;
std::cout << "Encoded: "<< encoded<< std::endl;
std::cout << "Decoded: "<< decoded<< std::endl;
return 0;
}
这个示例将输出:
Input: Hello, World!
Encoded: SGVsbG8sIFdvcmxkIQ==
Decoded: Hello, World!
这就是在C++中使用Base64编码的基本方法。请注意,这些示例仅用于演示目的,实际项目中可能需要更健壮的实现。