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

วิธีถอดรหัสสตริง (Decode Base64) ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธี ถอดรหัส Base64 (Decode) ใน Android พร้อมกับการ Encode เพื่อทดสอบ ใช้ android.util.Base64 และ StandardCharsets.UTF_8

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project กรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 2: จัดทำ Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_marginTop="30dp"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/edit_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter text to encode/decode" />
    <Button
        android:id="@+id/buttonPanel"
        android:text="Encode & Decode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_marginTop="10dp" />
    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_marginTop="10dp" />
</LinearLayout>

ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity {
    TextView textEncoded, textDecoded;
    EditText editQuery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editQuery = findViewById(R.id.edit_query);
        textEncoded = findViewById(R.id.text);
        textDecoded = findViewById(R.id.text1);

        findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {
                String input = editQuery.getText().toString();
                if (!input.isEmpty()) {
                    // 1. Encode
                    String encoded = Base64.encodeToString(
                            input.getBytes(StandardCharsets.UTF_8), 
                            Base64.NO_WRAP | Base64.URL_SAFE
                    );
                    textEncoded.setText("Encoded: " + encoded);

                    // 2. Decode
                    byte[] decodedBytes = Base64.decode(encoded, Base64.NO_WRAP | Base64.URL_SAFE);
                    String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
                    textDecoded.setText("Decoded: " + decoded);
                } else {
                    textEncoded.setText("Please enter text");
                    textDecoded.setText("");
                }
            }
        });
    }
}

การทดสอบ

รันแอป ป้อน "สวัสดีครับ" คลิกปุ่ม จะแสดง Encoded และ Decoded กลับมาเป็น "สวัสดีครับ" เหมือนเดิม

โค้ดสำคัญ: Encode & Decode แบบสมบูรณ์

// Encode
public String encodeBase64(String input) {
    return Base64.encodeToString(
        input.getBytes(StandardCharsets.UTF_8), 
        Base64.NO_WRAP | Base64.URL_SAFE
    );
}

// Decode
public String decodeBase64(String encoded) {
    byte[] decodedBytes = Base64.decode(encoded, Base64.NO_WRAP | Base64.URL_SAFE);
    return new String(decodedBytes, StandardCharsets.UTF_8);
}

จุดสำคัญ: ต้องใช้ Flag เดียวกันทั้ง Encode และ Decode

Encode FlagDecode Flagผลลัพธ์
DEFAULTDEFAULT✅ ถูกต้อง
NO_WRAP | URL_SAFENO_WRAP | URL_SAFE✅ ถูกต้อง (แนะนำ)
DEFAULTNO_WRAP❌ Error / ผิดพลาด
URL_SAFEDEFAULT❌ Error / ผิดพลาด

การจัดการ Error (Try-Catch)

public String safeDecode(String encoded) {
    try {
        byte[] decodedBytes = Base64.decode(encoded, Base64.NO_WRAP | Base64.URL_SAFE);
        return new String(decodedBytes, StandardCharsets.UTF_8);
    } catch (IllegalArgumentException e) {
        // Invalid Base64 string
        Log.e("Base64", "Decode failed: " + e.getMessage());
        return null;
    }
}

Android 8.0+ (API 26) ใช้ java.util.Base64

// Modern API (Java 8+)
import java.util.Base64;

String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(input.getBytes(StandardCharsets.UTF_8));
String decoded = new String(Base64.getUrlDecoder().decode(encoded), StandardCharsets.UTF_8);

กรณีใช้งานจริง

  • รับข้อมูล Base64 จาก Server/API แล้ว Decode ใช้งาน
  • ถอดรหัส JWT Token Payload (ส่วนกลาง) เพื่อดู Claims
  • Decode รูปภาพ Base64 จาก Data URI แสดงใน ImageView
  • ถอดรหัส Basic Auth Header

Decode รูปภาพ Base64 เป็น Bitmap

public Bitmap decodeBase64ToBitmap(String base64Image) {
    try {
        byte[] decodedBytes = Base64.decode(base64Image, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
    } catch (Exception e) {
        return null;
    }
}