[Python]43行で作るBasic認証
1.Basic認証
Basic認証のやりとりをターミナルで表現します。
2.コード
from base64 import b64encode
from base64 import b64decode
from time import sleep
def encode_pass(user_name, password):
to_utf8 = (user_name + ":" + password).encode("utf-8")
enc_pass = b64encode(to_utf8)
return enc_pass
#nobi:nobita => bm9iaTpub2JpdGE=
AUTH_INFO = "bm9iaTpub2JpdGE="
user_name = input("ユーザー名を入力してください:")
password= input("パスワードを入力してください:")
request_info = encode_pass(user_name, password)
request_header = """\n<Request Info>
/hoge HTTP/1.1 #メソッド名忘れました(心の中でGETを挿入して見てください)
Host:nobita.jp
Authorization: Basic {0}
""".format(request_info.decode())
print(request_header)
print("-" * 10)
success_header = """\n<Response Info>
HTTP/1.1 200 OK
"""
sleep(1)
error_header = """\n<Response Info>
HTTP/1.1 401 Unauthorized
"""
if AUTH_INFO == request_info.decode():
print(success_header)
print("-" * 10)
print("盗聴者:「おっ、平文で流れている!」")
print("(解析中..)")
decode_result = b64decode(request_info).decode()
sleep(1)
user_info = decode_result.split(":")
user_name = user_info[0]
password = user_info[1]
print(f"盗聴者「ユーザー名が{user_name}でパスワードが{password}だな。ニヤ(・∀・)ニヤ」")
else:
print(error_header)
3. 実行結果
認証成功
認証失敗
この記事が気に入ったらサポートをしてみませんか?