Java Base64编码使用介绍

Base64编码介绍
    BASE64 编码是一种常用的字符编码,Base64编码本质上是一种将二进制数据转成文本数据的方案。
但base64不是安全领域下的加密解密算法。能起到安全作用的效果很差,而且很容易破解,他核心作用应该是传输数据的正确性,有些网关或系统只能使用ASCII字符。
Base64就是用来将非ASCII字符的数据转换成ASCII字符的一种方法,而且base64特别适合在http,mime协议下快速传输数据。


使用场景

1.对数据传输过程中不可见字符的处理;
2.将图片二进制转为Base64编码嵌入网页,可有效减少HTTP请求图片带来性能提升;



Java对于Base64编码的支持
这里只讲原生JDK支持,足够你用的,别搞些第三方的:

package com.dylan.security;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.Base64;

/**
 * Base64编码测试类
 *
 * @author xusucheng
 * @create 2017-12-19
 **/
public class TestBase64 {
    public static final String toEncode="Hello Base64!";

    /**
     * jdk8以前
     * @throws IOException
     */
    public static void TestBase64Old() throws IOException {
        //编码
        BASE64Encoder encoder=new BASE64Encoder();
        String encoded = encoder.encode(toEncode.getBytes());
        System.out.println("编码后:"+encoded);

        //解码
        BASE64Decoder decoder=new BASE64Decoder();
        byte[] decoded = decoder.decodeBuffer(encoded);
        System.out.println("解码后:"+new String(decoded));

    }

    /**
     * jdk1.8后
     */
    public static void TestBase64New(){
        //编码
        String encoded = Base64.getEncoder().encodeToString(toEncode.getBytes());
        System.out.println("编码后:"+encoded);
        //解码
        byte[] decoded = Base64.getDecoder().decode(encoded);
        System.out.println("解码后:"+new String(decoded));
    }


    public static void main(String[] args) throws IOException {
        System.out.println("Before JDK1.8:");
        TestBase64Old();
        System.out.println("After JDK1.8:");
        TestBase64New();
    }
}

输出:

Before JDK1.8:
编码后:SGVsbG8gQmFzZTY0IQ==
解码后:Hello Base64!
From JDK1.8:
加密后:SGVsbG8gQmFzZTY0IQ==
解码后:Hello Base64!


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值