默認Base64編碼的字符串,用於網絡傳輸是不安全的,由於Base64編碼使用的標準字典含有「+」,「/」。html
規則以下:安全
//nonSafeBase64 到 safeBase64
'+' ------>> '-'網絡
'/' ------>> '_'app
//safeBase64 到 nonSafeBase64
'-' ------>> '+'編碼
'_' ------>> '/'spa
字符串長度%4的餘數,補'='code
//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(""); }