티스토리 뷰
원래 C++에서도 C의 go-to 문과 같이 이슈가 되는것이 많지만
C++을 제대로 시작한지 매우 조금 됐기 때문에 필요하다 싶으면 닥치는 대로
가져가 썻다(....)
//상속, 프렌드 등등 아무것도 모른다. C++에 익숙해지기 위해 만들었다..
특히 std::bitset을 써서 8비트와 6비트씩 끊는걸 구현했는데 매우 만족스러웠다.
예전에 C에서 짯던 코드와 비교하면 확실히 깨끗해졌다.
C++을 좀 더 공부해서 내가 만들고 싶은 프로그램을 만들고 싶다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <bitset> | |
typedef unsigned int u_int; | |
std::string const INDEX_TABLE = | |
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
class BASE64 | |
{ | |
public: | |
std::string userDefStr; | |
std::string encStr; | |
std::string decStr; | |
void encoding(std::string); | |
void decoding(std::string); | |
BASE64() {}; | |
BASE64(std::string Str) : userDefStr(Str) {}; | |
}; | |
void BASE64::encoding(std::string plainStr) | |
{ | |
std::string encStr; | |
std::string divStr; | |
std::string bin; | |
u_int index; | |
for (auto i : plainStr) | |
{ // character to binary (00000000b) | |
bin += std::bitset<8>(i).to_string(); | |
} | |
if (bin.length() % 6) | |
{ | |
for (u_int i = 0; i <= bin.length() % 6; i++) | |
{ | |
bin += '0'; | |
} | |
} | |
for (u_int i = 0; i < bin.length() / 6; i++) | |
{ | |
divStr = std::bitset<6>(&bin[6 * i]).to_string(); | |
index = std::bitset<8>(divStr).to_ulong(); | |
encStr += INDEX_TABLE[index]; | |
} | |
for (u_int i = 0; i < encStr.length() % 4; i++) | |
{ | |
encStr += '='; // padding | |
} | |
BASE64::encStr = encStr + '\0'; | |
} | |
void BASE64::decoding(std::string encedStr) | |
{ | |
std::string decStr; | |
std::string bin; | |
u_int mapTable[64]; | |
u_int temp = 0; | |
for (auto i : encedStr) | |
{ | |
if (i == '=') | |
break; | |
mapTable[temp++] = INDEX_TABLE.find(i); | |
} | |
for (u_int i = 0; i < temp; i++) | |
{ | |
bin += std::bitset<6>(mapTable[i]).to_string(); | |
} | |
for (u_int i = 0; i < bin.length() / 8; i++) | |
{ | |
temp = std::bitset<8>(&bin[i * 8]).to_ulong(); | |
decStr += static_cast<char>(temp); | |
} | |
BASE64::decStr = decStr + '\0'; | |
} | |
int main(void) | |
{ | |
BASE64 plain("VGhpc19Jc19CQVNFNjRfRW4vRGVDcnlwdF9Ub29sX19DKys="); | |
plain.encoding(plain.userDefStr); | |
plain.decoding(plain.userDefStr); | |
std::cout << "Encrypted String : " << plain.encStr << std::endl; | |
std::cout << "Decrypted String : " << plain.decStr << std::endl; | |
return 0; | |
} |
Encrypted String : VkdocGMxOUpjMTlDUVZORk5qUmZSVzR2UkdWRGNubHdkRjlVYjI5c1gxOURLeXM9
Decrypted String : This_Is_BASE64_En/DeCrypt_Tool__C++