반응형
C++ base64 encoding
/*
<Function Description>
base64 encoding 함수.
<parameter>
in : 평문 문자열.
<return>
out : base64 encoding 문자열.
*/
std::string base64_encode(const std::string &in) {
typedef unsigned char uchar;
std::string out;
int val = 0, valb = -6;
for (uchar c : in) {
val = (val << 8) + c;
valb += 8;
while (valb >= 0) {
out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6) out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[((val << 8) >> (valb + 8)) & 0x3F]);
while (out.size() % 4) out.push_back('=');
return out;
}
C++ base64 decoding
/*
<Function Description>
base64 decode 함수.
<parameter>
in : base64 encoding 문자열.
<return>
out : base64 decoding 문자열.
*/
std::string base64_decode(const std::string &in) {
typedef unsigned char uchar;
static const std::string b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
std::vector<int> T(256, -1);
for (int i = 0; i < 64; i++)
T[b[i]] = i;
int val = 0, valb = -8;
for (uchar c : in) {
if (T[c] == -1)
break;
val = (val << 6) + T[c];
valb += 6;
if (valb >= 0) {
out.push_back(char((val >> valb) & 0xFF));
valb -= 8;
}
}
return out;
}
반응형
'코딩 > C and C++' 카테고리의 다른 글
malloc calloc realloc의 차이점 (0) | 2022.10.03 |
---|---|
C++ gtest (0) | 2022.01.02 |
C++ WMI library사용 (0) | 2021.12.22 |
C++ windows 로컬 그룹 정책 확인 (1) | 2021.12.22 |
C++ Windows console 결과 영어로 출력 (0) | 2021.12.22 |