ตัวเข้ารหัสและถอดรหัส Base64: แปลงข้อความเป็น Base64 และกลับกัน
เครื่องมือออนไลน์ฟรีสำหรับการเข้ารหัสข้อความเป็น Base64 หรือถอดรหัสสตริง Base64 กลับเป็นข้อความ รองรับการเข้ารหัส Base64 แบบมาตรฐานและแบบ URL-safe พร้อมการแปลงทันที
ตัวเข้ารหัส/ถอดรหัส Base64
แปลงข้อความเป็นและจากการเข้ารหัส Base64
เอกสารประกอบการใช้งาน
Base64 Encoder and Decoder
Introduction
Base64 เป็นโค้ดดิ้งแบบไบนารีเป็นข้อความที่แสดงข้อมูลไบนารีในรูปแบบสตริง ASCII ออกแบบมาเพื่อส่งข้อมูลที่เก็บในรูปแบบไบนารีผ่านช่องทางที่รองรับเนื้อหาข้อความได้อย่างเชื่อถือได้เท่านั้น การเข้ารหัส Base64 จะแปลงข้อมูลไบนารีให้เป็นชุดของ 64 ตัวอักษร (จึงเป็นชื่อ) ที่สามารถส่งผ่านโปรโตคอลที่เป็นข้อความได้อย่างปลอดภัยโดยไม่เกิดการเสียหายของข้อมูล
ชุดอักษร Base64 ประกอบด้วย:
- ตัวอักษรพิมพ์ใหญ่ A-Z (26 ตัวอักษร)
- ตัวอักษรพิมพ์เล็ก a-z (26 ตัวอักษร)
- หลัก 0-9 (10 ตัวอักษร)
- ตัวอักษรเพิ่มเติมอีกสองตัว ซึ่งมักจะเป็น "+" และ "/" (2 ตัวอักษร)
เครื่องมือนี้ช่วยให้คุณสามารถเข้ารหัสข้อความเป็นรูปแบบ Base64 หรือถอดรหัสสตริง Base64 กลับไปยังข้อความต้นฉบับได้อย่างง่ายดาย โดยเฉพาะอย่างยิ่งสำหรับนักพัฒนา มืออาชีพด้าน IT และผู้ที่ทำงานกับข้อมูลที่ต้องการส่งผ่านช่องทางที่เป็นข้อความอย่างปลอดภัย
วิธีการทำงานของการเข้ารหัส Base64
กระบวนการเข้ารหัส
การเข้ารหัส Base64 ทำงานโดยการแปลงกลุ่มของไบต์สามตัว (24 บิต) ของข้อมูลไบนารีเป็นสี่ตัวอักษร Base64 ขั้นตอนการทำงานมีดังนี้:
- แปลงข้อความที่ป้อนเป็นการแทนค่าไบนารี (ใช้การเข้ารหัส ASCII หรือ UTF-8)
- จัดกลุ่มข้อมูลไบนารีเป็นชิ้นส่วนขนาด 24 บิต (3 ไบต์)
- แยกแต่ละชิ้นส่วนขนาด 24 บิตออกเป็นสี่กลุ่มขนาด 6 บิต
- แปลงแต่ละกลุ่มขนาด 6 บิตเป็นตัวอักษร Base64 ที่สอดคล้องกัน
เมื่อความยาวของข้อมูลนำเข้าไม่สามารถหารด้วย 3 ได้ จะมีการเพิ่มการเติมด้วยตัวอักษร "=" เพื่อรักษาสัดส่วน 4:3 ของความยาวเอาต์พุตต่อความยาวนำเข้า
การแทนค่าทางคณิตศาสตร์
สำหรับลำดับของไบต์ ตัวอักษร Base64 ที่สอดคล้องกัน จะถูกคำนวณดังนี้:
โดยที่ แทนตัวอักษรที่ ในอักษร Base64
กระบวนการถอดรหัส
การถอดรหัส Base64 จะกลับกระบวนการเข้ารหัส:
- แปลงแต่ละตัวอักษร Base64 เป็นค่าขนาด 6 บิต
- เชื่อมต่อค่าขนาด 6 บิตเหล่านี้
- จัดกลุ่มบิตเป็นชิ้นส่วนขนาด 8 บิต (ไบต์)
- แปลงแต่ละไบต์เป็นตัวอักษรที่สอดคล้องกัน
การเติม
เมื่อจำนวนไบต์ที่ต้องการเข้ารหัสไม่สามารถหารด้วย 3 ได้ จะมีการเติมดังนี้:
- หากเหลือไบต์หนึ่ง จะถูกแปลงเป็นตัวอักษร Base64 สองตัวตามด้วย "=="
- หากเหลือไบต์สอง จะถูกแปลงเป็นตัวอักษร Base64 สามตัวตามด้วย "="
ตัวอย่าง
มาลองเข้ารหัสข้อความ "Hello" เป็น Base64 กัน:
- การแทนค่า ASCII ของ "Hello": 72 101 108 108 111
- การแทนค่าไบนารี: 01001000 01100101 01101100 01101100 01101111
- การจัดกลุ่มเป็นชิ้นส่วนขนาด 6 บิต: 010010 000110 010101 101100 011011 000110 1111
- ชิ้นส่วนสุดท้ายมีเพียง 4 บิต จึงเติมด้วยศูนย์: 010010 000110 010101 101100 011011 000110 111100
- การแปลงเป็นเลขฐานสิบ: 18, 6, 21, 44, 27, 6, 60
- การค้นหาในอักษร Base64: S, G, V, s, b, G, 8
- ผลลัพธ์คือ "SGVsbG8="
สังเกตการเติม "=" ที่ท้ายเพราะความยาวของข้อมูลนำเข้า (5 ไบต์) ไม่สามารถหารด้วย 3 ได้
สูตร
สูตรทั่วไปสำหรับการคำนวณความยาวของสตริงที่เข้ารหัส Base64 คือ:
โดยที่ แทนฟังก์ชันเพดาน (การปัดขึ้นไปยังจำนวนเต็มที่ใกล้ที่สุด)
กรณีการใช้งาน
การเข้ารหัส Base64 ใช้กันอย่างแพร่หลายในแอปพลิเคชันต่างๆ:
-
ไฟล์แนบในอีเมล: MIME (Multipurpose Internet Mail Extensions) ใช้ Base64 เพื่อเข้ารหัสไฟล์แนบไบนารีในอีเมล
-
Data URLs: ฝังภาพเล็กๆ ฟอนต์ หรือทรัพยากรอื่นๆ โดยตรงใน HTML, CSS หรือ JavaScript โดยใช้สคีม่า
data:
-
การสื่อสาร API: ส่งข้อมูลไบนารีอย่างปลอดภัยใน JSON payloads หรือรูปแบบ API ที่เป็นข้อความอื่นๆ
-
การจัดเก็บข้อมูลไบนารีในรูปแบบข้อความ: เมื่อข้อมูลไบนารีต้องการจัดเก็บใน XML, JSON หรือรูปแบบข้อความอื่นๆ
-
ระบบการตรวจสอบสิทธิ์: การตรวจสอบสิทธิ์พื้นฐานใน HTTP ใช้การเข้ารหัส Base64 (แม้ว่าไม่ใช่เพื่อความปลอดภัย แต่เพื่อการเข้ารหัส)
-
การเข้ารหัส: เป็นส่วนหนึ่งของโปรโตคอลและระบบการเข้ารหัสต่างๆ โดยมักใช้สำหรับการเข้ารหัสคีย์หรือใบรับรอง
-
ค่าในคุกกี้: การเข้ารหัสโครงสร้างข้อมูลที่ซับซ้อนเพื่อจัดเก็บในคุกกี้
ทางเลือก
แม้ว่า Base64 จะใช้กันอย่างแพร่หลาย แต่ก็มีทางเลือกอื่นๆ ที่อาจเหมาะสมกว่าในบางสถานการณ์:
-
URL-safe Base64: ตัวแปรที่ใช้ "-" และ "_" แทน "+" และ "/" เพื่อหลีกเลี่ยงปัญหาการเข้ารหัส URL เหมาะสำหรับข้อมูลที่จะรวมอยู่ใน URL
-
Base32: ใช้ชุดอักษร 32 ตัว ส่งผลให้เอาต์พุตยาวขึ้นแต่มีความอ่านง่ายและไม่ไวต่อการใช้ตัวพิมพ์ใหญ่พิมพ์เล็ก
-
การเข้ารหัส Hex: การแปลงเป็นเลขฐานสิบหกอย่างง่าย ซึ่งมีประสิทธิภาพน้อยกว่า (ทำให้ขนาดเพิ่มขึ้นเป็นสองเท่า) แต่เรียบง่ายและรองรับอย่างกว้างขวาง
-
การส่งข้อมูลไบนารี: สำหรับไฟล์ขนาดใหญ่หรือเมื่อประสิทธิภาพมีความสำคัญ การส่งข้อมูลไบนารีโดยตรงผ่านโปรโตคอลเช่น HTTP โดยมี header Content-Type ที่เหมาะสมจะดีกว่า
-
การบีบอัด + Base64: สำหรับข้อมูลข้อความขนาดใหญ่ การบีบอัดก่อนการเข้ารหัสสามารถลดการเพิ่มขนาดได้
-
การจัดรูปแบบ JSON/XML: สำหรับข้อมูลที่มีโครงสร้าง การใช้การจัดรูปแบบ JSON หรือ XML แบบเนทีฟอาจเหมาะสมกว่าการเข้ารหัส Base64
ประวัติ
การเข้ารหัส Base64 มีรากฐานมาจากการคอมพิวเตอร์และระบบการสื่อสารในช่วงแรกที่ข้อมูลไบนารีต้องถูกส่งผ่านช่องทางที่ออกแบบมาสำหรับข้อความ
การระบุอย่างเป็นทางการของ Base64 ถูกเผยแพร่ครั้งแรกในปี 1987 ใน RFC 989 ซึ่งกำหนด Privacy Enhanced Mail (PEM) ซึ่งต่อมาได้รับการปรับปรุงใน RFC 1421 (1993) และ RFC 2045 (1996, เป็นส่วนหนึ่งของ MIME)
คำว่า "Base64" มาจากการที่การเข้ารหัสใช้ตัวอักษร ASCII 64 ตัวเพื่อแทนข้อมูลไบนารี การเลือกใช้ 64 ตัวอักษรนี้เป็นการตั้งใจ เนื่องจาก 64 เป็นเลขยกกำลังของ 2 (2^6) ซึ่งทำให้การแปลงระหว่างไบนารีและ Base64 มีประสิทธิภาพ
ตลอดระยะเวลาหลายปี มีตัวแปรหลายตัวของ Base64 เกิดขึ้น:
- Standard Base64: ตามที่กำหนดใน RFC 4648 โดยใช้ A-Z, a-z, 0-9, +, / และ = สำหรับการเติม
- URL-safe Base64: ใช้ - และ _ แทน + และ / เพื่อหลีกเลี่ยงปัญหาการเข้ารหัส URL
- Filename-safe Base64: คล้ายกับ URL-safe ออกแบบมาเพื่อใช้ในชื่อไฟล์
- Modified Base64 สำหรับ IMAP: ใช้ในโปรโตคอล IMAP โดยมีชุดอักษรพิเศษที่แตกต่างกัน
แม้ว่าจะมีอายุมากกว่า 30 ปี แต่ Base64 ยังคงเป็นเครื่องมือพื้นฐานในคอมพิวเตอร์สมัยใหม่ โดยเฉพาะอย่างยิ่งกับการเพิ่มขึ้นของแอปพลิเคชันเว็บและ API ที่พึ่งพาฟอร์แมตข้อมูลที่เป็นข้อความอย่างหนัก เช่น JSON
ตัวอย่างโค้ด
นี่คือตัวอย่างการเข้ารหัสและถอดรหัส Base64 ในภาษาการเขียนโปรแกรมต่างๆ:
1// JavaScript Base64 Encoding/Decoding
2function encodeToBase64(text) {
3 return btoa(text);
4}
5
6function decodeFromBase64(base64String) {
7 try {
8 return atob(base64String);
9 } catch (e) {
10 throw new Error("Invalid Base64 string");
11 }
12}
13
14// Example usage
15const originalText = "Hello, World!";
16const encoded = encodeToBase64(originalText);
17console.log("Encoded:", encoded); // SGVsbG8sIFdvcmxkIQ==
18
19try {
20 const decoded = decodeFromBase64(encoded);
21 console.log("Decoded:", decoded); // Hello, World!
22} catch (error) {
23 console.error(error.message);
24}
25
1# Python Base64 Encoding/Decoding
2import base64
3
4def encode_to_base64(text):
5 # Convert string to bytes and then encode
6 text_bytes = text.encode('utf-8')
7 base64_bytes = base64.b64encode(text_bytes)
8 return base64_bytes.decode('utf-8')
9
10def decode_from_base64(base64_string):
11 try:
12 # Convert base64 string to bytes and then decode
13 base64_bytes = base64_string.encode('utf-8')
14 text_bytes = base64.b64decode(base64_bytes)
15 return text_bytes.decode('utf-8')
16 except Exception as e:
17 raise ValueError(f"Invalid Base64 string: {e}")
18
19# Example usage
20original_text = "Hello, World!"
21encoded = encode_to_base64(original_text)
22print(f"Encoded: {encoded}") # SGVsbG8sIFdvcmxkIQ==
23
24try:
25 decoded = decode_from_base64(encoded)
26 print(f"Decoded: {decoded}") # Hello, World!
27except ValueError as e:
28 print(e)
29
1// Java Base64 Encoding/Decoding
2import java.util.Base64;
3import java.nio.charset.StandardCharsets;
4
5public class Base64Example {
6 public static String encodeToBase64(String text) {
7 byte[] textBytes = text.getBytes(StandardCharsets.UTF_8);
8 byte[] encodedBytes = Base64.getEncoder().encode(textBytes);
9 return new String(encodedBytes, StandardCharsets.UTF_8);
10 }
11
12 public static String decodeFromBase64(String base64String) {
13 try {
14 byte[] base64Bytes = base64String.getBytes(StandardCharsets.UTF_8);
15 byte[] decodedBytes = Base64.getDecoder().decode(base64Bytes);
16 return new String(decodedBytes, StandardCharsets.UTF_8);
17 } catch (IllegalArgumentException e) {
18 throw new IllegalArgumentException("Invalid Base64 string: " + e.getMessage());
19 }
20 }
21
22 public static void main(String[] args) {
23 String originalText = "Hello, World!";
24 String encoded = encodeToBase64(originalText);
25 System.out.println("Encoded: " + encoded); // SGVsbG8sIFdvcmxkIQ==
26
27 try {
28 String decoded = decodeFromBase64(encoded);
29 System.out.println("Decoded: " + decoded); // Hello, World!
30 } catch (IllegalArgumentException e) {
31 System.err.println(e.getMessage());
32 }
33 }
34}
35
1<?php
2// PHP Base64 Encoding/Decoding
3function encodeToBase64($text) {
4 return base64_encode($text);
5}
6
7function decodeFromBase64($base64String) {
8 $decoded = base64_decode($base64String, true);
9 if ($decoded === false) {
10 throw new Exception("Invalid Base64 string");
11 }
12 return $decoded;
13}
14
15// Example usage
16$originalText = "Hello, World!";
17$encoded = encodeToBase64($originalText);
18echo "Encoded: " . $encoded . "\n"; // SGVsbG8sIFdvcmxkIQ==
19
20try {
21 $decoded = decodeFromBase64($encoded);
22 echo "Decoded: " . $decoded . "\n"; // Hello, World!
23} catch (Exception $e) {
24 echo "Error: " . $e->getMessage() . "\n";
25}
26?>
27
1// C# Base64 Encoding/Decoding
2using System;
3using System.Text;
4
5class Base64Example
6{
7 public static string EncodeToBase64(string text)
8 {
9 byte[] textBytes = Encoding.UTF8.GetBytes(text);
10 return Convert.ToBase64String(textBytes);
11 }
12
13 public static string DecodeFromBase64(string base64String)
14 {
15 try
16 {
17 byte[] base64Bytes = Convert.FromBase64String(base64String);
18 return Encoding.UTF8.GetString(base64Bytes);
19 }
20 catch (FormatException)
21 {
22 throw new FormatException("Invalid Base64 string");
23 }
24 }
25
26 static void Main()
27 {
28 string originalText = "Hello, World!";
29 string encoded = EncodeToBase64(originalText);
30 Console.WriteLine($"Encoded: {encoded}"); // SGVsbG8sIFdvcmxkIQ==
31
32 try
33 {
34 string decoded = DecodeFromBase64(encoded);
35 Console.WriteLine($"Decoded: {decoded}"); // Hello, World!
36 }
37 catch (FormatException e)
38 {
39 Console.WriteLine($"Error: {e.Message}");
40 }
41 }
42}
43
1# Ruby Base64 Encoding/Decoding
2require 'base64'
3
4def encode_to_base64(text)
5 Base64.strict_encode64(text)
6end
7
8def decode_from_base64(base64_string)
9 begin
10 Base64.strict_decode64(base64_string)
11 rescue ArgumentError => e
12 raise "Invalid Base64 string: #{e.message}"
13 end
14end
15
16# Example usage
17original_text = "Hello, World!"
18encoded = encode_to_base64(original_text)
19puts "Encoded: #{encoded}" # SGVsbG8sIFdvcmxkIQ==
20
21begin
22 decoded = decode_from_base64(encoded)
23 puts "Decoded: #{decoded}" # Hello, World!
24rescue StandardError => e
25 puts "Error: #{e.message}"
26end
27
1// Go Base64 Encoding/Decoding
2package main
3
4import (
5 "encoding/base64"
6 "fmt"
7)
8
9func encodeToBase64(text string) string {
10 return base64.StdEncoding.EncodeToString([]byte(text))
11}
12
13func decodeFromBase64(base64String string) (string, error) {
14 bytes, err := base64.StdEncoding.DecodeString(base64String)
15 if err != nil {
16 return "", fmt.Errorf("invalid Base64 string: %v", err)
17 }
18 return string(bytes), nil
19}
20
21func main() {
22 originalText := "Hello, World!"
23 encoded := encodeToBase64(originalText)
24 fmt.Println("Encoded:", encoded) // SGVsbG8sIFdvcmxkIQ==
25
26 decoded, err := decodeFromBase64(encoded)
27 if err != nil {
28 fmt.Println("Error:", err)
29 } else {
30 fmt.Println("Decoded:", decoded) // Hello, World!
31 }
32}
33
1// Swift Base64 Encoding/Decoding
2import Foundation
3
4func encodeToBase64(_ text: String) -> String? {
5 if let data = text.data(using: .utf8) {
6 return data.base64EncodedString()
7 }
8 return nil
9}
10
11func decodeFromBase64(_ base64String: String) -> String? {
12 if let data = Data(base64Encoded: base64String) {
13 return String(data: data, encoding: .utf8)
14 }
15 return nil
16}
17
18// Example usage
19let originalText = "Hello, World!"
20if let encoded = encodeToBase64(originalText) {
21 print("Encoded: \(encoded)") // SGVsbG8sIFdvcmxkIQ==
22
23 if let decoded = decodeFromBase64(encoded) {
24 print("Decoded: \(decoded)") // Hello, World!
25 } else {
26 print("Error: Could not decode Base64 string")
27 }
28} else {
29 print("Error: Could not encode text")
30}
31
1' Excel VBA Base64 Encoding/Decoding
2' Note: This requires a reference to Microsoft XML, v6.0
3Function EncodeToBase64(text As String) As String
4 Dim xmlObj As Object
5 Set xmlObj = CreateObject("MSXML2.DOMDocument")
6
7 Dim xmlNode As Object
8 Set xmlNode = xmlObj.createElement("b64")
9
10 xmlNode.DataType = "bin.base64"
11 xmlNode.nodeTypedValue = StrConv(text, vbFromUnicode)
12
13 EncodeToBase64 = xmlNode.text
14
15 Set xmlNode = Nothing
16 Set xmlObj = Nothing
17End Function
18
19Function DecodeFromBase64(base64String As String) As String
20 On Error GoTo ErrorHandler
21
22 Dim xmlObj As Object
23 Set xmlObj = CreateObject("MSXML2.DOMDocument")
24
25 Dim xmlNode As Object
26 Set xmlNode = xmlObj.createElement("b64")
27
28 xmlNode.DataType = "bin.base64"
29 xmlNode.text = base64String
30
31 DecodeFromBase64 = StrConv(xmlNode.nodeTypedValue, vbUnicode)
32
33 Set xmlNode = Nothing
34 Set xmlObj = Nothing
35 Exit Function
36
37ErrorHandler:
38 DecodeFromBase64 = "Error: Invalid Base64 string"
39End Function
40
41' Usage in a worksheet:
42' =EncodeToBase64("Hello, World!")
43' =DecodeFromBase64("SGVsbG8sIFdvcmxkIQ==")
44
1# R Base64 Encoding/Decoding
2# Requires the 'base64enc' package
3# install.packages("base64enc")
4library(base64enc)
5
6encode_to_base64 <- function(text) {
7 # Convert text to raw bytes, then encode
8 text_raw <- charToRaw(text)
9 base64_encoded <- base64encode(text_raw)
10 return(rawToChar(base64_encoded))
11}
12
13decode_from_base64 <- function(base64_string) {
14 tryCatch({
15 # Convert base64 string to raw, then decode
16 base64_raw <- charToRaw(base64_string)
17 decoded_raw <- base64decode(base64_raw)
18 return(rawToChar(decoded_raw))
19 }, error = function(e) {
20 stop(paste("Invalid Base64 string:", e$message))
21 })
22}
23
24# Example usage
25original_text <- "Hello, World!"
26encoded <- encode_to_base64(original_text)
27cat("Encoded:", encoded, "\n") # SGVsbG8sIFdvcmxkIQ==
28
29tryCatch({
30 decoded <- decode_from_base64(encoded)
31 cat("Decoded:", decoded, "\n") # Hello, World!
32}, error = function(e) {
33 cat("Error:", e$message, "\n")
34})
35
1% MATLAB Base64 Encoding/Decoding
2function demo_base64()
3 originalText = 'Hello, World!';
4
5 % Encode
6 encoded = encode_to_base64(originalText);
7 fprintf('Encoded: %s\n', encoded); % SGVsbG8sIFdvcmxkIQ==
8
9 % Decode
10 try
11 decoded = decode_from_base64(encoded);
12 fprintf('Decoded: %s\n', decoded); % Hello, World!
13 catch e
14 fprintf('Error: %s\n', e.message);
15 end
16end
17
18function encoded = encode_to_base64(text)
19 % Convert text to uint8 array and encode
20 bytes = uint8(text);
21 encoded = base64encode(bytes);
22end
23
24function decoded = decode_from_base64(base64String)
25 try
26 % Decode base64 string to uint8 array
27 bytes = base64decode(base64String);
28 decoded = char(bytes);
29 catch
30 error('Invalid Base64 string');
31 end
32end
33
1// C Base64 Encoding/Decoding using OpenSSL
2#include <stdio.h>
3#include <string.h>
4#include <openssl/bio.h>
5#include <openssl/evp.h>
6#include <openssl/buffer.h>
7#include <stdint.h>
8
9char* encode_to_base64(const char* input) {
10 BIO *bio, *b64;
11 BUF_MEM *bufferPtr;
12
13 b64 = BIO_new(BIO_f_base64());
14 bio = BIO_new(BIO_s_mem());
15 bio = BIO_push(b64, bio);
16
17 BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
18 BIO_write(bio, input, strlen(input));
19 BIO_flush(bio);
20 BIO_get_mem_ptr(bio, &bufferPtr);
21
22 char* result = (char*)malloc(bufferPtr->length + 1);
23 memcpy(result, bufferPtr->data, bufferPtr->length);
24 result[bufferPtr->length] = '\0';
25
26 BIO_free_all(bio);
27
28 return result;
29}
30
31char* decode_from_base64(const char* input) {
32 BIO *bio, *b64;
33 size_t length = strlen(input);
34 char* buffer = (char*)malloc(length);
35
36 b64 = BIO_new(BIO_f_base64());
37 bio = BIO_new_mem_buf(input, -1);
38 bio = BIO_push(b64, bio);
39
40 BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
41 int decoded_length = BIO_read(bio, buffer, length);
42
43 if (decoded_length <= 0) {
44 free(buffer);
45 BIO_free_all(bio);
46 return NULL; // Invalid Base64 input
47 }
48
49 buffer[decoded_length] = '\0';
50
51 BIO_free_all(bio);
52
53 return buffer;
54}
55
56int main() {
57 const char* original_text = "Hello, World!";
58
59 char* encoded = encode_to_base64(original_text);
60 printf("Encoded: %s\n", encoded); // SGVsbG8sIFdvcmxkIQ==
61
62 char* decoded = decode_from_base64(encoded);
63 if (decoded) {
64 printf("Decoded: %s\n", decoded); // Hello, World!
65 free(decoded);
66 } else {
67 printf("Error: Invalid Base64 string\n");
68 }
69
70 free(encoded);
71
72 return 0;
73}
74
1// Rust Base64 Encoding/Decoding
2use base64::{encode, decode};
3use std::str;
4
5fn encode_to_base64(text: &str) -> String {
6 encode(text)
7}
8
9fn decode_from_base64(base64_string: &str) -> Result<String, String> {
10 match decode(base64_string) {
11 Ok(bytes) => {
12 match str::from_utf8(&bytes) {
13 Ok(text) => Ok(text.to_string()),
14 Err(e) => Err(format!("Invalid UTF-8 sequence: {}", e))
15 }
16 },
17 Err(e) => Err(format!("Invalid Base64 string: {}", e))
18 }
19}
20
21fn main() {
22 let original_text = "Hello, World!";
23 let encoded = encode_to_base64(original_text);
24 println!("Encoded: {}", encoded); // SGVsbG8sIFdvcmxkIQ==
25
26 match decode_from_base64(&encoded) {
27 Ok(decoded) => println!("Decoded: {}", decoded), // Hello, World!
28 Err(e) => println!("Error: {}", e)
29 }
30}
31
กรณีขอบและข้อพิจารณา
เมื่อทำงานกับการเข้ารหัสและถอดรหัส Base64 ให้ระวังข้อพิจารณาที่สำคัญเหล่านี้:
-
อักขระ Unicode และ Non-ASCII: เมื่อเข้ารหัสข้อความที่มีอักขระที่ไม่ใช่ ASCII ให้แน่ใจว่ามีการเข้ารหัสตัวอักษรที่ถูกต้อง (โดยปกติคือ UTF-8) ก่อนการเข้ารหัส Base64
-
การเติม: Base64 มาตรฐานใช้การเติมด้วยตัวอักษร "=" เพื่อให้แน่ใจว่าความยาวเอาต์พุตเป็นหลายของ 4 บางการใช้งานอนุญาตให้ละเว้นการเติมซึ่งอาจทำให้เกิดปัญหาความเข้ากันได้
-
การตัดบรรทัด: การใช้งาน Base64 แบบดั้งเดิมจะใส่การตัดบรรทัด (โดยปกติทุกๆ 76 ตัวอักษร) เพื่อความอ่านง่าย แต่แอปพลิเคชันสมัยใหม่มักจะละเว้นสิ่งเหล่านี้
-
Base64 ที่ปลอดภัยสำหรับ URL: Base64 มาตรฐานใช้ตัวอักษร "+" และ "/" ซึ่งมีความหมายพิเศษใน URL สำหรับบริบทของ URL ให้ใช้ Base64 ที่ปลอดภัยสำหรับ URL ซึ่งจะเปลี่ยนเป็น "-" และ "_"
-
ช่องว่าง: เมื่อถอดรหัส บางการใช้งานจะอนุญาตให้ละเลยช่องว่าง ขณะที่บางการใช้งานต้องการข้อมูลที่ถูกต้อง
-
การเพิ่มขนาด: การเข้ารหัส Base64 จะเพิ่มขนาดข้อมูลประมาณ 33% (4 ไบต์เอาต์พุตสำหรับทุก 3 ไบต์นำเข้า)
-
ประสิทธิภาพ: การเข้ารหัส/ถอดรหัส Base64 อาจใช้ทรัพยากรมากสำหรับข้อมูลขนาดใหญ่ พิจารณาใช้วิธีการสตรีมสำหรับไฟล์ขนาดใหญ่
อ้างอิง
คำติชม
คลิกที่ feedback toast เพื่อเริ่มให้คำแนะนำเกี่ยวกับเครื่องมือนี้
เครื่องมือที่เกี่ยวข้อง
ค้นพบเครื่องมือเพิ่มเติมที่อาจมีประโยชน์สำหรับการทำงานของคุณ