Base64 在编码特殊字符时不起作用

Base64 doesn't work when encoding special characters

本文关键字:不起作用 特殊字符 编码 Base64      更新时间:2023-10-16

我正在使用我在github链接到b64.c上找到的base64库,当我编码ASCII字符串时,它可以正常工作,但是当我尝试编码一个二进制文件时,例如图像,它行不通。以下是我用来在文件中读取的代码段。

hello.txt

héllo

hello.txt具有唯一的特殊角色。如果特殊字符只是一个常规角色,则可以。

main.c

int main()
{
    FILE *fp=NULL;
    char *buf=NULL, *str1="héllo", *str2="hello";
    int i=0;
    size_t fsize=0, bytes_read=0;
    fp=fopen("hello.txt", "rb");
    fseek(fp, 0, SEEK_END);
    fsize=ftell(fp);
    rewind(fp);
    buf=(char*)malloc(sizeof(char)*(fsize));
    //buf[fsize]='';
    bytes_read=fread(buf, 1, fsize, fp);
    if( bytes_read!=fsize ) exit(-1);
    fclose(fp);
    printf("encoded=%sn", b64_encode((const unsigned char*)buf, fsize));
    getchar();
    return 0;
}

ENCODE.C//具有函数base64_encode

char *b64_encode(const unsigned char* src, size_t len)
{
    int i=0, j=0;
    char *enc=NULL;
    size_t size=0;
    unsigned char buf[4], tmp[3];
    // alloc
    enc=(char*)malloc(0);
    if( enc==NULL )
    {
        perror("enc");
        return NULL;
    }
    while( len-- )
    {
        tmp[i++]=*(src++);
        if( i==3 )
        {
            buf[0]=( tmp[0]&0xfc )>>2;
            buf[1]=( ( tmp[0]&0x03 )<<4 )+( ( tmp[1]&0xf0 )>>4 );
            buf[2]=( ( tmp[1]&0x0f )<<2 )+( ( tmp[1]&0xc0 )>>6 );
            buf[3]=tmp[2]&0x3f;
            /*
             * alloc 4 bytes for 'enc' and then translate
             * each encoded buffer part by index from
             * the base64 table into 'enc' unsigned char array
            */
            enc=(char*)realloc(enc, size+4);
            for( i=0; i<4; ++i )
            {
                enc[size++]=b64_table[buf[i]];
            }
            // reset index
            i=0;
        }
    }
    if( i>0 )
    {
        // fill 'tmp' with '' at most 3 times
        for( j=i; j<3; ++j )
        {
            tmp[j]='';
        }
        // perform same codes as above
        buf[0]=( tmp[0]&0xfc )>>2;
        buf[1]=( ( tmp[0]&0x03 )<<4 )+( ( tmp[1]&0xf0 )>>4 );
        buf[2]=( ( tmp[1]&0x0f )<<2 )+( ( tmp[1]&0xc0 )>>6 );
        buf[3]=tmp[2]&0x3f;
        // same write to enc with new allocation
        for( j=0; j<i+1; ++j )
        {
            enc=(char*)realloc(enc, size+1);
            enc[size++]=b64_table[buf[j]];
        }
        while( ( i++ )<3 )
        {
            enc=(char*)realloc(enc, size+1);
            enc[size++]='=';
        }
    }
    enc=(char*)realloc(enc, size+1);
    enc[size]='';
    return enc;
}

OUPUT通过程序

aOnsbG9=

使用UTF-8

保存后
aMPpbGxv  

预期输出

aMOpbGxv

PS。我将文件读取为二进制文件,因为它具有特殊字符,因为以后我想在二进制数据(例如图像或视频)中阅读。

问题在于函数b64_encode:

buf[2]=( ( tmp[1]&0x0f )<<2 )+( ( tmp[1]&0xc0 )>>6 );

应该是

buf[2]=( ( tmp[1]&0x0f )<<2 )+( ( tmp[2]&0xc0 )>>6 );

一定要在两个术时修复此操作。