Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách mã hóa chuỗi (Encode String) Base64 trên Android

Giới thiệu

Mã hóa Base64 chuyển đổi dữ liệu binary/text thành chuỗi ASCII an toàn để truyền qua mạng, lưu trữ, hoặc embed trong JSON/XML. Android cung cấp android.util.Base64.

Triển khai

Bước 1: Tạo dự án

Android Studio → New Project → Empty Activity.

Bước 2: 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:padding="16dp"
    android:gravity="center_horizontal"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edit_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Nhập chuỗi cần encode"
        android:inputType="textMultiLine"
        android:minHeight="100dp" />

    <Button
        android:id="@+id/buttonPanel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Encode Base64" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textSize="16sp"
        android:textStyle="bold"
        tools:text="Kết quả Base64..." />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    EditText editQuery;
    TextView textResult;

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

        findViewById(R.id.buttonPanel).setOnClickListener(v -> {
            String input = editQuery.getText().toString();
            if (input.isEmpty()) {
                textResult.setText("Vui lòng nhập chuỗi");
                return;
            }
            
            // Encode Base64
            String encoded = Base64.encodeToString(
                input.getBytes(), 
                Base64.DEFAULT
            );
            
            textResult.setText("Encoded:\n" + encoded);
        });
    }
}

Các Flag Base64 quan trọng

FlagMô tảDùng khi
DEFAULTTiêu chuẩn RFC 4648, có newline sau 76 charsChung, email, MIME
NO_WRAPKhông ngắt dòngJSON, URL, Header, SharedPreferences
URL_SAFEThay +/ thành -_ (an toàn cho URL)Query param, filename, token
NO_PADDINGBỏ ký tự '=' ở cuốiKhi decode tự handle padding

Ví dụ các flag

String input = "Hello Android Base64 Encoding Test";

// DEFAULT (có newline)
String d = Base64.encodeToString(input.getBytes(), Base64.DEFAULT);
// "SGVsbG8gQW5kcm9pZCBCYXNlNjQgRW5jb2RpbmcgVGVzdA==\n"

// NO_WRAP (liền mạch)
String nw = Base64.encodeToString(input.getBytes(), Base64.NO_WRAP);
// "SGVsbG8gQW5kcm9pZCBCYXNlNjQgRW5jb2RpbmcgVGVzdA=="

// URL_SAFE (an toàn URL)
String us = Base64.encodeToString(input.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP);
// "SGVsbG8gQW5kcm9pZCBCYXNlNjQgRW5jb2RpbmcgVGVzdA=="

// Kết hợp flags
String custom = Base64.encodeToString(input.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);

Encode Bitmap/Image thành Base64

// Bitmap → Base64
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String base64Image = Base64.encodeToString(imageBytes, Base64.NO_WRAP);
// Sử dụng: "data:image/png;base64," + base64Image
Lưu ý: Base64 làm tăng kích thước ~33%. Không phải mã hóa bảo mật (dễ decode). Dùng cho encoding, không phải encryption.