Base64编码 / Base64解码

复制结果

知识百科

Base64编码

使用 MIME base64 对数据进行编码。
设计此种编码是为了使二进制数据可以通过非纯 8-bit 的传输层传输,例如电子邮件的主体。
Base64 编码数据要比原始数据多占用 33% 左右的空间。
采用 Base64 编码具有不可读性,需要解码后才能阅读。

Base64解码

对使用 MIME base64 编码的数据进行解码。

Example

示例 #1 PHP 7.1+ base64编码的例子
<?php
$str = 'This is an encoded string';
echo base64_encode($str);

输出的结果:VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

示例 #2 PHP 7.1+ base64解码的例子
<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);

输出的结果:This is an encoded string

示例 #3 Go 1.18 base64编码的例子
package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    data := []byte("This is an encoded string")
    str := base64.StdEncoding.EncodeToString(data)
    fmt.Println(str)
}

输出的结果:VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

示例 #4 Go 1.18 base64解码的例子
package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    str := "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw=="
    data, err := base64.StdEncoding.DecodeString(str)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Printf("%s\n", data)
}

输出的结果:This is an encoded string