Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Base64 Data Encoding ใน Python

โมดูล base64 แปลงข้อมูล Binary เป็น subset ของ ASCII เหมาะสำหรับส่งผ่านโปรโตคอลข้อความธรรมดา (email, URL, HTTP POST) ตาม RFC 3548 รองรับ Base16, Base32, Base64, Ascii85, Base85

อินเทอร์เฟซสมัยใหม่ (Modern Interface)

ฟังก์ชันคำอธิบาย
b64encode(data)เข้ารหัส bytes-like object เป็น Base64 คืนค่า bytes
b64decode(data)ถอดรหัส Base64 bytes/ASCII string คืนค่า bytes
urlsafe_b64encode(data)Base64 URL-safe: - แทน +, _ แทน /
urlsafe_b64decode(data)ถอดรหัส URL-safe Base64

ตัวอย่าง: Encode/Decode String


>>> import base64
>>> string = 'Python programming'
>>> enc_string = string.encode()
>>> enc_string
b'Python programming'

>>> b64_estring = base64.b64encode(enc_string)
>>> b64_estring
b'UHl0aG9uIHByb2dyYW1taW5n'

>>> dec_string = b64_estring.decode()
>>> dec_string
'UHl0aG9uIHByb2dyYW1taW5n'

>>> b1 = dec_string.encode()
>>> b1
b'UHl0aG9uIHByb2dyYW1taW5n'

>>> d = base64.b64decode(b1)
>>> d
b'Python programming'

>>> original = d.decode()
>>> original
'Python programming'

อินเทอร์เฟซแบบเก่า (Legacy Interface) - ไฟล์

ฟังก์ชันคำอธิบาย
encode(input, output)เข้ารหัสไฟล์ binary input เขียน base64 ลง output (file objects)
decode(input, output)ถอดรหัส base64 จาก input เขียน binary ลง output (file objects)

ตัวอย่าง: Encode/Decode ไฟล์


# 1. สร้างไฟล์ต้นฉบับ
>>> f1 = open('file.txt', 'wb')
>>> f1.write('Simple is better than complex'.encode())
>>> f1.close()

# 2. Encode ไฟล์
>>> f1 = open('file.txt', 'rb')
>>> f2 = open('file.dat', 'wb')
>>> base64.encode(f1, f2)
>>> f1.close()
>>> f2.close()

# file.dat เนื้อหา:
# U2ltcGxlIGlzIGJldHRlciB0aGFuIGNvbXBsZXg=

# 3. Decode กลับ
>>> f1 = open('file.dat', 'rb')
>>> f2 = open('filenew.txt', 'wb')
>>> base64.decode(f1, f2)
>>> f1.close()
>>> f2.close()

# filenew.txt จะมีข้อความเดิม

Base64 Alphabets

มาตรฐาน: A-Z, a-z, 0-9, +, /, = (padding)
URL-safe: A-Z, a-z, 0-9, -, _, = (padding)

การใช้งานทั่วไป

  • เข้ารหัสรูปภาพ/ไฟล์สำหรับ embed ใน HTML/CSS/JSON (Data URI)
  • ส่งข้อมูล Binary ผ่าน API ที่รองรับเฉพาะ Text
  • Basic Authentication Header (username:password → Base64)
  • JWT Tokens, SAML, Digital Certificates