Java编码方式:Base64编码与解码

1、Base64 算法介绍

Base64 是一种基于 64 个可打印字符来表示二进制数据的表示方法。它主要用于在不支持二进制数据的场合(如电子邮件、URL、文件系统名等)传输二进制数据。严格来说 Base64 并不是一种加密/解密算法,而是一种编码方式。Base64 不生成密钥,通过 Base64 编码后的密文就可以直接“翻译”为明文。

Java 提供了对 Base64 编码和解码的支持,通过 java.util.Base64 类来实现。

java.util.Base64 类提供了以下几种主要的功能:

  1. 编码:将二进制数据(如字节数组)编码为 Base64 字符串。
  2. 解码:将 Base64 字符串解码为二进制数据(如字节数组)。
  3. URL 和 MIME 编码:提供了对 URL 和 MIME 安全的 Base64 编码和解码。

Base64字符映射表:

Base64 编码的核心思想是将每三个字节的二进制数据转换为四个字节的文本数据。这四个字节的文本数据是从一个包含64个字符的集合中选择的,这个集合通常包括大写字母A-Z、小写字母a-z、数字0-9、加号(+)、斜杠(/),以及一个用于填充的等号(=)。 

2、Base64 编码与解码

【实例】Java 中使用 Base64 算法,对数据进行编码与解码。

(1)创建 Base64Util 类(Base64编码工具类)。

package com.pjb.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * Base64编码工具类
 * @author pan_junbiao
 **/
public class Base64Util
{
    //字符编码
    public final static String charsetName = StandardCharsets.UTF_8.name();

    /**
     * Base64编码
     */
    public static String encode(String data) throws Exception
    {
        //执行编码
        String encode = Base64.getEncoder().encodeToString(data.getBytes(charsetName));
        return encode;
    }

    /**
     * Base64解码
     */
    public static String decode(String data) throws Exception
    {
        byte[] decode = Base64.getDecoder().decode(data.getBytes(charsetName));
        return new String(decode);
    }

    /**
     * URL安全编码
     */
    public static String urlEncode(String url) throws Exception
    {
        String urlEncode = Base64.getUrlEncoder().encodeToString(url.getBytes(charsetName));
        return urlEncode;
    }

    /**
     * URL安全解码
     */
    public static String urlDecode(String data) throws Exception
    {
        byte[] urlDecode = Base64.getUrlDecoder().decode(data.getBytes(charsetName));
        return new String(urlDecode);
    }

    /**
     * 文件(图片、Word、PDF) 转 Base64 编码
     *
     * @param file 文件
     */
    public static String fileEncode(File file) throws IOException
    {
        String base64Str = null;
        FileInputStream fin = null;
        BufferedInputStream bin = null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout = null;
        try
        {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            // io
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while (len != -1)
            {
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            // 刷新此输出流,强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            // Base64字符编码
            base64Str = Base64.getEncoder().encodeToString(bytes).trim();
        } catch (IOException e)
        {
            e.getMessage();
        } finally
        {
            try
            {
                fin.close();
                bin.close();
                bout.close();
            } catch (IOException e)
            {
                e.getMessage();
            }
        }
        return base64Str;
    }

    /**
     * 文件(图片、Word、PDF) 转 Base64 解码(另存文件)
     *
     * @param base64Content Base64 字符串
     * @param filePath      另存文件路径
     */
    public static void fileDecode(String base64Content, String filePath) throws IOException
    {
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try
        {
            // Base64解码到字符数组
            byte[] bytes = Base64.getDecoder().decode(base64Content);
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File(filePath);
            File path = file.getParentFile();
            if (!path.exists())
            {
                path.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            // io
            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while (length != -1)
            {
                bos.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            // 刷新此输出流,强制写出所有缓冲的输出字节
            bos.flush();
        } catch (IOException e)
        {
            e.getMessage();
        } finally
        {
            try
            {
                bis.close();
                fos.close();
                bos.close();
            } catch (IOException e)
            {
                e.getMessage();
            }
        }
    }
}

(2)使用 Base64 算法,对数据进行编码与解码。

/**
 * 使用 Base64 编码与解码
 */
@Test
public void testBase64() throws Exception
{
    String data = "您好,欢迎访问 pan_junbiao的博客";

    // 1、使用 Base64 编码
    String encode = Base64Util.encode(data);

    // 2、使用 Base64 解码
    String decode = Base64Util.decode(encode);

    // 3、打印结果
    System.out.println("原始数据:" + data);
    System.out.println("编码数据:" + encode);
    System.out.println("解码数据:" + decode);
}

执行结果:

3、URL 编码与解码

对 URL 进行 Base64 编码的主要原因是为了确保 URL 在传输过程中的安全性和可读性。

【实例】Java 中使用 Base64 算法,对 URL 进行编码与解码。

/**
 * 使用 Base64 对 URL 编码与解码
 */
@Test
public void testUrlBase64() throws Exception
{
    String url = "https://blog.csdn.net/pan_junbiao?account=登录账号&password=登录密码";

    // 1、使用 URL安全编码
    String urlEncode = Base64Util.urlEncode(url);

    // 2、使用 Base64 解码
    String urlDecode = Base64Util.urlDecode(urlEncode);

    // 3、打印结果
    System.out.println("原始数据:" + url);
    System.out.println("编码数据:" + urlEncode);
    System.out.println("解码数据:" + urlDecode);
}

执行结果:

4、文件的编码与解码

对文件进行 Base64 编码的原因主要涉及到数据的传输、存储和嵌入等多个方面。

【实例】 Java 中使用 Base64 算法,对文件(如:图片、Word、PDF 等) 进行编码与解码。

/**
 * 使用 Base64 对 文件 编码与解码
 */
@Test
public void testFileBase64() throws Exception
{
    String filePath1 = "E:/file/1.png"; //文件地址
    String filePath2 = "E:/file/2.png"; //文件另存地址

    // 1、使用 Base64 将文件编码
    String fileEncode = Base64Util.fileEncode(new File(filePath1));

    // 2、使用 Base64 将文件解码(另存文件)
    Base64Util.fileDecode(fileEncode, filePath2);
}

执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pan_junbiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值