大橙子网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

C++:通过openssl完成base64编解码-创新互联

举例如下:

10年积累的网站建设、成都网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有晋源免费网站建设让你可以放心的选择与我们合作。
#includeusing namespace std;

int openssl_base64_encode(const unsigned char* in, int inlen, char* out, int* outlen, bool newline)
{
    BIO* b64 = BIO_new(BIO_f_base64());
    BIO* bmem = BIO_new(BIO_s_mem());
    if (!b64 || !bmem) {
        fprintf(stderr, "fail to BIO_new\n");
        return -1;
    }

    b64 = BIO_push(b64, bmem);
    if (!newline)
        BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // ignore newlines, write everything in one line

    *outlen = BIO_write(b64, in, inlen);
    if (*outlen<= 0 || *outlen != inlen) {
        fprintf(stderr, "fail to BIO_write\n");
        return -1;
    }

    BIO_flush(b64);
    BUF_MEM* buf = nullptr;
    BIO_get_mem_ptr(b64, &buf);
    *outlen = buf->length;
    memcpy(out, buf->data, *outlen);
    BIO_free_all(b64);
    return 0;
}

int openssl_base64_decode(const char* in, int inlen, unsigned char* out, int* outlen, bool newline)
{
    BIO* b64 = BIO_new(BIO_f_base64());
    BIO* bmem = BIO_new_mem_buf(in, inlen);
    if (!b64 || !bmem) {
        fprintf(stderr, "fail to BIO_new\n");
        return -1;
    }
    
    b64 = BIO_push(b64, bmem);
    if (!newline)
        BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // ignore newlines, write everything in one line
        
    *outlen = BIO_read(b64, out, inlen);
    if (*outlen<= 0) {
        fprintf(stderr, "fail to BIO_read\n");
        return -1;
    }

    BIO_free_all(b64);
    return 0;
}

void base64_test()
{
    char jwtHeader[] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
    printf("jwt header origin:%s\n", jwtHeader);
    unsigned char jwtDecode[256] = {0};
    int jwtDecodeLen = 0;
    openssl_base64_decode(jwtHeader, strlen(jwtHeader), jwtDecode, &jwtDecodeLen, false);
    jwtDecode[jwtDecodeLen] = '\0';
    printf("jwt header decode:%s\n", jwtDecode);

    char jwtEncode[256] = {0};
    int jwtEncodeLen = 0;
    openssl_base64_encode(jwtDecode, strlen((char*)jwtDecode), jwtEncode, &jwtEncodeLen, false);
    jwtEncode[jwtEncodeLen] = '\0';
    printf("jwt header encode:%s\n", jwtEncode);
}

int main()
{
    base64_test();  
    return 0;
}

编译时需要加上链接库参数:-lssl -lcrypto

运行程序输出:
jwt header origin:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
jwt header decode:{"alg":"HS256","typ":"JWT"}
jwt header encode:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

注:base64编码后的字符串长度的计算方法为:向上取整(原始字节数 / 3) * 4

也就是:base64_len = ( strlen(str_in)/3 + 1) * 4;

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


本文标题:C++:通过openssl完成base64编解码-创新互联
链接分享:http://dzwzjz.com/article/esdpo.html
在线咨询
服务热线
服务热线:028-86922220
TOP