使用 libtomcrypt 的 C/C++ Base64 编解码器
问题:
在 C/C++ 中你想从/到 Base64 编码/解码某些内容。libtomcrypt 是 WTFPL 许可的,因此为商业和非商业项目提供了好的选择。
解决方案
使用这些代码片段:
base64_libtomcrypt.cpp
#include <tomcrypt.h>
/**
* 将给定字符串编码为 Base64
* @param input 要 Base64 编码的输入字符串
* @param inputSize 要解码的输入大小
* @return 编码字符串的 Base64 编码版本
*/
std::string encodeBase64(const char* input, const unsigned long inputSize) {
unsigned long outlen = inputSize + (inputSize / 3.0) + 16;
unsigned char* outbuf = new unsigned char[outlen]; //Reserve output memory
base64_encode((unsigned char*) input, inputSize, outbuf, &outlen);
std::string ret((char*) outbuf, outlen);
delete[] outbuf;
return ret;
}
/**
* 将给定字符串编码为 Base64
* @param input 要 Base64 编码的输入字符串
* @return 编码字符串的 Base64 编码版本
*/
std::string encodeBase64(const std::string& input) {
return encodeBase64(input.c_str(), input.size());
}
/**
* 解码 Base64 编码的字符串。
* @param input 要解码的输入字符串
* @return 表示输入的 Base64 解码数据的字符串(二进制)
*/
std::string decodeBase64(const std::string& input) {
unsigned char* out = new unsigned char[input.size()];
unsigned long outlen = input.size();
base64_decode((unsigned char*) input.c_str(), input.size(), out, &outlen);
std::string ret((char*) out, outlen);
delete[] out;
return ret;
}Check out similar posts by category:
C/C++, Cryptography
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow