C++实现 safaBase64编码跟nonSafeBase64编码的转换
默认Base64编码的字符串,用于网络传输是不安全的,因为Base64编码使用的标准字典含有“+”,“/”。
规则如下:
//nonSafeBase64 到 safeBase64
'+' ------>> '-'
'/' ------>> '_'
//safeBase64 到 nonSafeBase64
'-' ------>> '+'
'_' ------>> '/'
字符串长度%4的余数,补'='
//safeBase64 非safeBase64 想换转换 std::string safeAndNonsafeBase64Change(std::string inputStr, int mode) { if( mode == 1) //safe -->> nonsafe { for(int i = 0; i < inputStr.size(); i++) { if(inputStr[i] == '-') { inputStr[i] = '+'; continue; } if(inputStr[i] == '_') { inputStr[i] = '/'; continue; } } int remainder = inputStr.length()%4; while(remainder--) { inputStr.append("="); } return inputStr; } else if (mode == 2) //nonsafe -->> safe { for(int i = 0; i < inputStr.size(); i++) { if(inputStr[i] == '+') { inputStr[i] = '-'; continue; } if(inputStr[i] == '/') { inputStr[i] = '_'; continue; } if(inputStr[i] == '=') { //inputStr[i] = ''; inputStr.pop_back(); continue; } } return inputStr; } else return std::string(""); }