Base64算法

作者: flycloud_hz | 来源:发表于2017-10-20 16:06 被阅读0次

    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;
    }
    

    相关文章

      网友评论

        本文标题:Base64算法

        本文链接:https://www.haomeiwen.com/subject/mhyvuxtx.html