C语言中的Base64编码 [英] Base64 encoding in C

查看:67
本文介绍了C语言中的Base64编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想将RSA加密消息转换为Base64格式,以便通过TCP/IP套接字作为字符缓冲区发送加密消息.

如何在C程序中进行Base64编码?散发出一些亮光:-)

在此先谢谢您.

Hi,

I want to convert RSA encrypted message to Base64 format inorder to send encrypted message via TCP/IP socket as a character buffer.

How to do the Base64 encoding in C program ??? Shed some bright light :-)

Thanks in advance.

推荐答案

请耐心等待!您只在八分钟前发布了该代码,并且已经用较少的信息将其重新发布了吗?
Have a little patience! You only posted this eight minutes ago, and you repost it with less information already?


Base64编码非常简单,您应在阅读一些内容后半小时内完成编码例程文档.作为起点,请参见Wikipedia上的 Base64 [
Base64 encoding is very simple, you should complete the encoding routine in half a hour, after reading some documentation. As starting point see Base64 at Wikipedia[^].


这就是您想要的(在C ++中):

This is what you want (in C++):

static const std::string base64_chars =  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                         "abcdefghijklmnopqrstuvwxyz"
                                         "0123456789+/";


std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len)
{
    std::string ret;
    int i = 0;
    int j = 0;
    unsigned char char_array_3[3];
    unsigned char char_array_4[4];

    while (in_len--) {
        char_array_3[i++] = *(bytes_to_encode++);
        if (i == 3) {
            char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
            char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
            char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
            char_array_4[3] = char_array_3[2] & 0x3f;

            for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]];
            i = 0;
        }
    }

    if (i) {
        for(j = i; j < 3; j++) char_array_3[j] = '\0';

        char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
        char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
        char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
        char_array_4[3] = char_array_3[2] & 0x3f;

        for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]];

        while((i++ < 3)) ret += '=';
    }

    return ret;
}



希望对您有帮助



Hope it helps


这篇关于C语言中的Base64编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆