Base64算法

0x0 Base64介绍

Base64用于二进制转为字符串,编码后空间大1/3左右。

0x1 代码实现

h文件

class Base64Crypt {
public:
    static int Encode(const std::string& input, std::string& output);
    static int Decode(const std::string& input, std::string& output);
};

cpp文件

int Base64Crypt::Decode(const std::string &input, std::string &output) {
    if (input.empty())
        return -1;

    BIO* b64 = BIO_new(BIO_f_base64());
    if (b64) {
        int buf_len = input.length();
        char* buf = new char[buf_len];
        if (buf) {
            BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
            BIO* bmem = BIO_new_mem_buf(const_cast<char*>(input.c_str()), input.length());
            if (bmem) {
                bmem = BIO_push(b64, bmem);
                int len = BIO_read(bmem, buf, buf_len);
                if (len > 0)
                    output = std::string(buf, len);
            }
            delete[] buf;
        }
        BIO_free_all(b64);
    }
    return 0;
}

int Base64Crypt::Encode(const std::string &input, std::string &output) {
    if (input.empty())
        return -1;

    BIO* b64 = BIO_new(BIO_f_base64());
    if (b64) {
        BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
        BIO* bmem = BIO_new(BIO_s_mem());
        if (bmem) {
            b64 = BIO_push(b64, bmem);
            BIO_write(b64, input.c_str(), input.length());
            BIO_flush(b64);
            BUF_MEM* buf_mem = NULL;
            BIO_get_mem_ptr(b64, &buf_mem);
            if (buf_mem)
                output = std::string(buf_mem->data, buf_mem->length);
        }
        BIO_free_all(b64);
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • [TOC] ##Assoc 显示或修改文件扩展名关联 Assoc [.Ext[=[Filetype]]] .Ex...
    btijjj阅读 384评论 0 1
  • Base64编码由来 Base64最早是用来解决电子邮件的传输问题。 传统的电子邮件是1982年定下技术规范的,详...
    Ashton阅读 2,616评论 0 6
  • 2017.2.7 最近好忙的。而且也没什么特别的事发生。 睡眠还是不好。一般都是看看简书的文章然后就昏迷的。昨天去...
    丶青木阅读 210评论 0 0
  • 一、Instrument工具介绍与使用 Instrument是性能分析、动态跟踪和分析OS X和iOS代码的测试工...
    TKkk阅读 3,254评论 1 28
  • 运营人员都知道消息推送对提高用户参与度的重要性。推送消息做的好,用户参与度会显著提高,反之,用户量也会跟着大打折扣...
    yuexiao0901阅读 568评论 0 1