diff options
Diffstat (limited to 'base64.cpp')
-rw-r--r-- | base64.cpp | 11 |
1 files changed, 7 insertions, 4 deletions
@@ -6,7 +6,7 @@ using namespace std; namespace Base64{ char alphabet[65]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - uint8_t revbet[128]={ + uint8_t revbet[128]={ //reverse look-up table of `alphabet` (for decoding) #define XX (127) XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX, //0-15 XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX, //16-31 @@ -19,6 +19,8 @@ namespace Base64{ #undef XX }; + //This is the standard base64 algorithm; most of the code deals with correct padding, actually. + //There are a lot of magic numbers here, but they should be obvious regarding the algorithm. string encode(const string &data){ int sz=data.size(); if(sz==0)return {}; @@ -50,24 +52,25 @@ namespace Base64{ return res; } + //The inverse of `encode`. string decode(const string &dataS){ int szS=dataS.size(); if(szS==0)return {}; uint8_t data[szS]; int sz=0; - for(char c : dataS){ + for(char c : dataS){ //First filter away all non-base64 characters (probably mostly newlines, if any) if(revbet[c&0x7f]!=127)data[sz++]=revbet[c&0x7f]; } int blocks=sz/4; int endlen; - if(sz%4==0){ + if(sz%4==0){ //Detect padding; tries to be nice and forgive bad padding if(data[sz-1]=='='){ blocks--; if(data[sz-2]=='=')endlen=1; else endlen=2; } else endlen=0; - } else endlen=sz%4-1; + } else endlen=sz%4-1; //padding not present... assume the data is OK sort-of? string res(3*blocks+endlen,'\0'); int x; for(int i=0;i<blocks;i++){ |