基于C++的Base64编解码实现

//base64.cpp
//

#include 
#include 

#include 
#include 

std::string base64encode(const char *infile,const char *outfile)
{
    int DataByte=0;
    unsigned char* Data=NULL;

    FILE *fp=fopen(infile,"rb");
    if(fp==NULL)
    {
         return "\0";
    }

    fseek(fp,0L,SEEK_END);
    DataByte=ftell(fp);
    Data=new unsigned char[DataByte+1];

    fseek(fp,0L,SEEK_SET);
    fread(Data,DataByte,1,fp);
    fclose(fp);    
    
    //code table
    const char EncodeTable[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    //return value
    std::string strEncode;
    unsigned char Tmp[4]={0};

    for(int i=0;i<(int)(DataByte/3);i++)
    {
        Tmp[1]=*Data++;
        Tmp[2]=*Data++;
        Tmp[3]=*Data++;

        strEncode+=EncodeTable[Tmp[1]>>2];
        strEncode+=EncodeTable[((Tmp[1]<<4) | (Tmp[2]>>4)) & 0x3F];

        strEncode+=EncodeTable[((Tmp[2]<<2) | (Tmp[3]>>6)) & 0x3F];
        strEncode+=EncodeTable[Tmp[3] & 0x3F];
    }

    //encode the remaining bytes
    int Mod=DataByte % 3;
    if(Mod==1)
    {
        Tmp[1]=*Data++;
        strEncode+=EncodeTable[(Tmp[1] & 0xFC)>>2];
        strEncode+=EncodeTable[((Tmp[1] & 0x03)<<4)];
        strEncode+="==";
    }

    else if(Mod==2)
    {
        Tmp[1]=*Data++;
        Tmp[2]=*Data++;
        strEncode+=EncodeTable[(Tmp[1] & 0xFC)>>2];
        strEncode+=EncodeTable[((Tmp[1] & 0x03)<<4) | ((Tmp[2] & 0xF0)>>4)];
        strEncode+=EncodeTable[((Tmp[2] & 0x0F)<<2)];
        strEncode+="=";
    }   
    
    //std::cout<>4);
        pszDecode[n+1]=((b[1] & 0xf)<<4) | ((b[2] & 0x3c)>>2);
        pszDecode[n+2]= ((b[2] & 0x3)<<6) | b[3];
 
        n+=3;
    }
 
    if( pszSource[nByteSrc-1]=='=' && pszSource[nByteSrc-2]=='=' )
    {
        b[0]=dekey[pszSource[i]];        
        b[1]=dekey[pszSource[i+1]];
        if(b[0]==-1 || b[1]==-1)
        {
            throw "bad base64 string";
        }

        pszDecode[n]=(b[0]<<2) | ((b[1] & 0x30)>>4);
        pszDecode[n+1]='\0';
    }
 
    if( pszSource[nByteSrc-1]=='=' && pszSource[nByteSrc-2] !='=' )
    {
        b[0]=dekey[pszSource[i]];        
        b[1]=dekey[pszSource[i+1]];
        b[2]=dekey[pszSource[i+2]];

        if(b[0]==-1 || b[1]==-1 || b[2]==-1)
        {
            throw "bad base64 string";
        }

        pszDecode[n]=(b[0]<<2) | ((b[1] & 0x30)>>4);
        pszDecode[n+1]=((b[1] & 0xf)<<4) | ((b[2] & 0x3c)>>2);
        pszDecode[n+2]='\0';
    }
 
    if( pszSource[nByteSrc-1] !='=' && pszSource[nByteSrc-2] !='=' )
    {
        pszDecode[n]='\0';
    }

    fp=fopen(outfile,"wb+");
    for(i=0;i

编译命令如下:

g++ -std=c++17 -o encdec.exe Base64.cpp

调用格式如下:

encdec.exe enc[dec] inputfile outputfile

你可能感兴趣的:(c++,base64,算法)