C++实现 base64 字符串编码解码(GCC编译)。

 /**
* @brief C++ base64 编解码
* @author wid
* @date 2013-20-25
*
* @note 若代码存在 bug 或程序缺陷, 请留言反馈, 谢谢!
*/ #include <iostream>
#include <string>
#include <ctime> //base64 编解码函数声明
std::string b64encodestring(const std::string &strString); //对 ASCII 字符串进行 base64 编码
std::string b64decodestring(const std::string &strString); //对 base64 编码后的字符串进行解码 //base64 编解码函数实现
/**
* @brief 对 ASCII 字符串进行 base64 编码
*
* @param strString 待编码的字符串
*
* @return srs::string 返回编码后的字符串
*
* @note 对于字符串中含有非 ASCII 字符串型的字符, 代码将抛出 std::string 型异常, 请捕获
*/
std::string b64encodestring(const std::string &strString)
{
int nByteSrc = strString.length();
std::string pszSource = strString; int i = ;
for(i; i < nByteSrc; i++)
if( pszSource[i] < || pszSource[i] > )
throw "can not encode Non-ASCII characters"; const char *enkey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string pszEncode(nByteSrc*/ + , '\0');
int nLoop = nByteSrc % == ? nByteSrc : nByteSrc - ;
int n = ;
for(i=; i < nLoop; i+= )
{
pszEncode[n] = enkey[pszSource[i]>>];
pszEncode[n+] = enkey[((pszSource[i]&)<<) | ((pszSource[i+] & 0xF0)>>)];
pszEncode[n+] = enkey[((pszSource[i+] & 0x0f)<<) | ((pszSource[i+] & 0xc0 )>>)];
pszEncode[n+] = enkey[pszSource[i+] & 0x3F];
n += ;
} switch(nByteSrc%)
{
case :
pszEncode[n] = '\0';
break; case :
pszEncode[n] = enkey[pszSource[i]>>];
pszEncode[n+] = enkey[((pszSource[i]&)<<) | ((&0xf0)>>)];
pszEncode[n+] = '=';
pszEncode[n+] = '=';
pszEncode[n+] = '\0';
break; case :
pszEncode[n] = enkey[pszSource[i]>>];
pszEncode[n+] = enkey[((pszSource[i]&)<<) | ((pszSource[i+]&0xf0)>>)];
pszEncode[n+] = enkey[(( pszSource[i+]&0xf)<< ) | ((&0xc0)>>)];
pszEncode[n+] = '=';
pszEncode[n+] = '\0';
break;
} return pszEncode.c_str();
} /**
* @brief 对 base64 编码后的字符串进行解码
*
* @param strString 待解码的字符串
*
* @return std::string 返回解码后的字符串
*
* @note 对于非base64编码的字符串或已损坏的base64字符串进行解码会抛出 std::string 型异常, 请捕获
*/
std::string b64decodestring(const std::string &strString)
{
int nByteSrc = strString.length();
std::string pszSource = strString; const int dekey[] = {
-, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -,
-, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -,
, // '+'
-, -, -,
, // '/'
, , , , , , , , , , // '0'-'9'
-, -, -, -, -, -, -,
, , , , , , , , , , , , ,
, , , , , , , , , , , , , // 'A'-'Z'
-, -, -, -, -, -,
, , , , , , , , , , , , ,
, , , , , , , , , , , , , // 'a'-'z'
}; if(nByteSrc% != )
throw "bad base64 string"; std::string pszDecode(nByteSrc*/+, '\0');
int nLoop = pszSource[nByteSrc-] == '=' ? nByteSrc - : nByteSrc;
int b[];
int i = , n = ;
for(i = ; i < nLoop; i += )
{
b[] = dekey[pszSource[i]]; b[] = dekey[pszSource[i+]];
b[] = dekey[pszSource[i+]]; b[] = dekey[pszSource[i+]];
if(b[] == - || b[] == - || b[] == - || b[] == -)
throw "bad base64 string"; pszDecode[n] = (b[] << ) | ((b[] & 0x30) >> );
pszDecode[n+] = ((b[] & 0xf) << ) | ((b[] & 0x3c) >> );
pszDecode[n+] = ((b[] & 0x3) << ) | b[]; n+=;
} if( pszSource[nByteSrc-] == '=' && pszSource[nByteSrc-] == '=' )
{
b[] = dekey[pszSource[i]]; b[] = dekey[pszSource[i+]];
if(b[] == - || b[] == -)
throw "bad base64 string"; pszDecode[n] = (b[] << ) | ((b[] & 0x30) >> );
pszDecode[n+] = '\0';
} if( pszSource[nByteSrc-] == '=' && pszSource[nByteSrc-] != '=' )
{
b[] = dekey[pszSource[i]]; b[] = dekey[pszSource[i+]];
b[] = dekey[pszSource[i+]];
if(b[] == - || b[] == - || b[] == -)
throw "bad base64 string"; pszDecode[n] = (b[] << ) | ((b[] & 0x30) >> );
pszDecode[n+] = ((b[] & 0xf) << ) | ((b[] & 0x3c) >> );
pszDecode[n+] = '\0';
} if( pszSource[nByteSrc-] != '=' && pszSource[nByteSrc-] != '=' )
pszDecode[n] = '\0'; return pszDecode;
} //测试
int main()
{
///编码测试
std::string str1 = "Hello, world!";
std::cout << "对Hello, world!进行base64编码: " << b64encodestring(str1) << std::endl; ///解码测试
std::string str2 = "SGVsbG8sIHdvcmxkIQ==";
std::cout << "对SGVsbG8sIHdvcmxkIQ==进行base64解码: " << b64decodestring(str2) << std::endl; ///编码耗时测试
std::string str3(, 'A'); //生成 10000000 长的字符串
std::cout << std::endl << "对 10000000 长的字符串进行编码耗时测试.." << std::endl;
size_t t0 = clock(); //编码计时开始
b64encodestring(str3);
std::cout << "测试结束, 耗时 " << clock() - t0 << "ms" << std::endl; ///解码耗时测试
std::string str4 = b64encodestring(str3); //得到长度为 10000000 的字符串base64编码后的字符串
std::cout << std::endl << "对 " << str4.length() << " 长的base64字符串进行解码耗时测试.." << std::endl;
size_t t1 = clock(); //解码计时开始
b64decodestring(str3);
std::cout << "测试结束, 耗时 " << clock() - t1 << "ms" << std::endl; return ;
}

运行测试结果:

若代码存在 bug 或程序缺陷, 请留言反馈, 谢谢。                                                                                                                                                                                                                                                                                                                                              

C++ Base64 编码 解码的更多相关文章

  1. OpenSSL 使用 base64 编码/解码

    简述 关于 OpenSSL 的介绍及安装请参见:Windows下编译OpenSSL 下面主要介绍有关 OpenSSL 使用 base64 编码/解码. 简述 编码解码 更多参考 编码/解码 #incl ...

  2. 利用openssl进行BASE64编码解码、md5/sha1摘要、AES/DES3加密解密

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  3. Javascript中Base64编码解码的使用实例

    Javascript为我们提供了一个简单的方法来实现字符串的Base64编码和解码,分别是window.btoa()函数和window.atob()函数. 1 var encodedStr = win ...

  4. Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net

    Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net 1. Base64编码, 1 1.1. 子模式 urlsafe Or  url  ...

  5. Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net

    Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net 1. Base64编码,1 1.1. 子模式 urlsafe Or  url u ...

  6. delphi Base64编码/解码及数据压缩/解压知识

    一.Base64编码/解码 一般用到的是Delphi自带的单元EncdDecd,当然还有第三方提供的单元或控件,其中我所接触到的认为比较好的有Indy的TIdMimeEncode / TIdMimeD ...

  7. Code:Base64 编码/解码

    ylbtech-Code:Base64 编码/解码 1. C#返回顶部 1.编码 byte[] inArray = new byte[msgTxt.Length]; int x; ; x < m ...

  8. 原来浏览器原生支持JS Base64编码解码 outside of the Latin1 range

    原来浏览器原生支持JS Base64编码解码 « 张鑫旭-鑫空间-鑫生活 https://www.zhangxinxu.com/wordpress/2018/08/js-base64-atob-bto ...

  9. 王小胖之 Base64编码/解码

    使用场景:编码网址作为URL参数,简单编码或加密数据,下载地址生成或解析. 实现功能:BASE64在线编码和解码. 数据实例:王小胖好啊,王小胖顶呱呱!! ~~ english 123 !@#$%^& ...

  10. Delphi Base64编码/解码及ZLib压缩/解压

    最近在写的程序与SOAP相关,所以用到了一些Base64编码/解码及数据压缩/解压方面的知识. 在这里来作一些总结:   一.Base64编码/解码   一般用到的是Delphi自带的单元EncdDe ...

随机推荐

  1. IE8下使用webuploader点击无反应的解决方法。

    在IE8开头添加如下代码. <meta http-equiv="X-UA-Compatible" content="IE=edge"> 即可解决,亲 ...

  2. 滚动div的动画

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  3. python异常处理、反射、socket

    一.isinstance 判断对象是否为类的实例 n1 = print isinstance(n1,int) class A: pass class B(A): pass b= B() print i ...

  4. Linux C学习笔记06--Tlist使用(编程工具篇)

    为了方便用VIM编程,安装了一个方便的小工具 taglist,下面是taglist使用的一些说明. 常用的taglist配置选项,可以根据自己的习惯进行配置: Tlist_Ctags_Cmd选项用于指 ...

  5. Web前端之CSS_day1-2

    1.div和span div的语义是division“分割”: span的语义就是span“范围.跨度” div标签是一个容器级标签,里面什么都能放,甚至可以放div自己 span是一个“文本级”的标 ...

  6. gdb调式

    1.PCB版的相应目录下执行命令: gdbserver 10.18.13.84:5555 DvdPlayer 2.linux操作系统执行:(如果是android找到android项目路径下的gdb)m ...

  7. componentsSeparatedByString,componentsJoinedByString,componentsSeparatedByCharactersInSet

    将string字符串转换为array数组 NSArray  *array = [Str componentsSeparatedByString:@","]; ==反向方法 将arr ...

  8. 剑指offer题目51-60

    面试题51:数组中重复的数字 public class Solution { public boolean duplicate(int numbers[],int length,int [] dupl ...

  9. SMTP的相关命令

    SMTP是Simple Mail Transfer Protocol的简写. 邮件是日常工作.生活中不能缺少的一个工具,下面是邮件收发的流程. Image 邮件的发送,主要是通过SMTP协议来实现的. ...

  10. 统计学习方法笔记 Logistic regression

    logistic distribution 设X是连续随机变量,X服从逻辑斯谛分布是指X具有下列分布函数和密度函数: 式中,μ为位置参数,γ>0为形状参数. 密度函数是脉冲函数 分布函数是一条S ...