java:Base64编码解码方式

本文介绍了Java中三种不同的Base64编码和解码方式:1) 使用JDK自带包;2) 使用Bouncy Castle提供的Base64解密加密;3) 使用Commons Codec库的Base64方法。尽管所需包不同,但它们的运行结果相同。对于不能引入特定包的情况,可以参考链接提供的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.使用jdk自带包解码编码:

package com.cl;

import java.io.IOException;

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

public class JdkBase64 {

	private static String src="imooc security base64";
	
	public static void main(String[] args) {
		base64();
	}

	public static void base64(){
		BASE64Encoder encoder=new BASE64Encoder();
		String dst=encoder.encode(src.getBytes());
		System.out.println("encode:"+dst);
		BASE64Decoder decoder=new BASE64Decoder();
		try {
			System.out.println(new String(decoder.decodeBuffer(dst)));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

若遇到不能引入相关BASE64Decoder和BASE64Decoder包的话,可以用如下方法解决:

https://blog.youkuaiyun.com/erlian1992/article/details/79518416

2.使用Bouncy Caslte提供的包Base64解密加密:需要引入如下的包

以上两个包需要匹配jdk版本使用:具体可以在http://bouncycastle.org/latest_releases.html里查看和下载合适版本

package com.cl;

import org.bouncycastle.util.encoders.Base64;

public class BCBase64 {

	private static String src="imooc security base64";
	
	public static void main(String[] args) {
	BouncyCastleBase64();
	}
	
	public static void BouncyCastleBase64(){
		byte[] encode=Base64.encode(src.getBytes());
		System.out.println("encode:"+new String(encode));
		byte[] decode=Base64.decode(encode);
		System.out.println("decode:"+new String(decode));
	}

}

3使用Commons Codec的方法Base64解密加密:需要下载如下

以上包并不需要与jdk版本对应。

package com.cl;

import org.apache.commons.codec.binary.Base64;

public class CCBase64 {

	private static String src="imooc security base64";
	
	public static void main(String[] args) {
		CommonsCodecBase64();
	}
	
	public static void CommonsCodecBase64(){
		byte[] encode=Base64.encodeBase64(src.getBytes());
		System.out.println("encode:"+new String(encode));
		byte[] decode=Base64.decodeBase64(encode);
		System.out.println("decode:"+new String(decode));
		
	}

}

4三个的运行结果一致:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值