1. 程式人生 > 其它 >URL Safe base64 與 base64相互轉換

URL Safe base64 與 base64相互轉換

技術標籤:Javascriptbase64js正則表示式字串

為什麼需要base64?

ASCII碼一共規定了128個字元的編碼,這128個符號,範圍在[0,127]之間.
其中,[0,31],及127, 33個屬於不可列印的控制字元.

在電子郵件傳輸資訊時,有些郵件閘道器會把[0,31]這些控制字元給悄悄清除.
還有的早期程式,收到[128,255]之間的國際字元時,甚至會發生錯誤.

如何在不同郵件閘道器之間安全的傳輸控制字元,國際字元,甚至二進位制檔案?
於是作為MIME多媒體電子郵件標準的一部分—base64被開發出來.

什麼是url_safe base64編碼?

在上面的base64傳統編碼中會出現+, /兩個會被url直接轉義的符號,

因此如果希望通過url傳輸這些編碼字串,
我們需要先做傳base64編碼,隨後將+和/分別替換為- _兩個字元,在接收端則做相反的動作解碼

JS轉換方法

  /**
   * 解碼 URL Safe base64 -> base64
   * @description: URL Safe base64
   * '-' -> '+'
   * '_' -> '/'
   * 字串長度%4,補'='
   * @param {type} string
   * @return: Base64 string;
   */
  function urlSafeBase64Decode(
base64Str) { if (!base64Str) return; let safeStr = base64Str.replace(/-/g, '+').replace(/_/g, '/'); let num = safeStr.length % 4; return safeStr + '===='.substring(0, num); } /** * 編碼 base64 -> URL Safe base64 * @description: base64 * '+' -> '-' * '/' -> '_' * '=' -> '' * @param {type} string * @return: URL Safe base64 string; */
function urlSateBase64Encode(base64Str) { if (!base64Str) return; let safeStr = base64Str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '’); // const UriSafe = (src: string) => src.replace(/[+\/]/g, (m0) => m0 == '+' ? '-' : '_').replace(/=+$/m, ‘'); return safeStr }