0
0

URLセーフなBase64エンコーディングとデコーディングとは

Last updated at Posted at 2023-09-04

Base64エンコーディングした文字列をURLパラメータで送信を求められることがあります。Base64エンコーディングされた文字列にはURLに含められない+/=が含まれるため、URLセーフ に変換が必要です。

Base64エンコーディングとは

データを 64種類の文字 (アルファベット大文字小文字、0から9の数字)と+/=の記号のみを使って変換する方式。メールの添付ファイル送信などに使われます。

javascriptの場合

const encoded = btoa("String to be encoded")
    .replace(/=/g, "")
    .replace(/\+/g, "-")
    .replace(/\//g, "_");

javascriptの場合は btoa でBase64エンコーディングした後、+-に、/_に変換し、末尾の=は削除します。

デコードする場合は逆の操作をします。

const decoded = atob(encoded
    .replace(/-/g, "+")
    .replace(/_/g, "/"));

Pythonの場合

import base64

encoded = base64.urlsafe_b64encode("String to be encoded").decode('utf-8').replace('=', '')

pythonの場合、base64.urlsafe_b64encodeが使えますが、=の削除はマニュアルで行います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0