第八章

Go, C#, PHP 和 Shell

多语言环境下的 Base64 速查手册

Go 语言

Go 语言在 encoding/base64 包中提供了极其高效的实现。

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    msg := "Hello, World!"
    
    // 编码
    encoded := base64.StdEncoding.EncodeToString([]byte(msg))
    fmt.Println(encoded)

    // 解码
    decoded, _ := base64.StdEncoding.DecodeString(encoded)
    fmt.Println(string(decoded))
}

C# (.NET)

在 C# 中,使用 System.Convert 类进行转换。

using System;
using System.Text;

class Program {
    static void Main() {
        string original = "Hello, World!";
        byte[] bytes = Encoding.UTF8.GetBytes(original);

        // 编码
        string encoded = Convert.ToBase64String(bytes);
        Console.WriteLine(encoded);

        // 解码
        byte[] decodedBytes = Convert.FromBase64String(encoded);
        string decodedText = Encoding.UTF8.GetString(decodedBytes);
        Console.WriteLine(decodedText);
    }
}

PHP

PHP 提供了极其简单的内置函数。

$str = 'Hello, World!';

// 编码
$encoded = base64_encode($str);
echo $encoded;

// 解码
$decoded = base64_decode($encoded);
echo $decoded;

Linux Shell

Linux 系统通常预装了 base64 命令行工具,非常适合在脚本中使用。

# 编码字符串
echo -n "Hello, World!" | base64
# 输出: SGVsbG8sIFdvcmxkIQ==

# 解码字符串
echo "SGVsbG8sIFdvcmxkIQ==" | base64 -d
# 输出: Hello, World!

# 编码文件
base64 image.png > image_base64.txt

# 解码文件
base64 -d image_base64.txt > restored_image.png