温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在java中使用Base64进行加密与解密

发布时间:2021-03-15 17:10:47 来源:亿速云 阅读:284 作者:Leah 栏目:开发技术

怎么在java中使用Base64进行加密与解密?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

Base64加密与解密操作

package cn.mldn.demo;
import java.util.Base64;
public class JavaAPIDemo{
  public static void main(String[] args) throws Exception{
   String msg="www.mldn.cn";   //原始内容
   String encMsg=new String(Base64.getEncoder().encode(msg.getBytes()));//数据加密
   System.out.println(encMsg);    //输出密文
   String oldMsg=new String(Base64.getDecoder().decode(encMsg)); //数据解密
   System.out.println(oldMsg); //输出明文
  }
}

程序执行结果:
d3d3Lm1sZG4uY24=(密文)
www.mldn.cn(明文)

本程序直接利用Base64提供的方法获取了Base64.Encoder与Base64.Decoder实例化对象,并且对原始数据进行了加密与解密处理。但需要注意的是,由于Base64属于JDK的原始实现,所以单纯地加密是不安全的,此时为了获取更加安全的数据加密操作,可以利用盐值(salt)、自定义格式以及多次加密的方式来保证项目中的数据安全。

基于Base64定义复杂加密与解密操作

package cn.mldn.demo;
import java.util.Base64;

class StringUtil
{
	private static final String SALT="mldnjava"; //公共的盐值
	private static final int REPEAT=5;  //加密次数
	
	public static String encode(String str) {  //加密处理		
										
		String temp=str+"{"+SALT+"}";				//盐值对外不公布
		byte data[]=temp.getBytes();				//将字符串变为字节数组
		for(int x=0;x<REPEAT;x++)
			data=Base64.getEncoder().encode(data); //重复加密
		return new String(data);  //返回加密后的内容
	}
	
	public static String decode(String str) {
		byte data[]=str.getBytes();					//获取加密内容
		for(int x=0;x<REPEAT;x++)
			data=Base64.getDecoder().decode(data); //多次解密
		return new String(data).replaceAll("\\{\\w+\\}",""); //删除盐值格式
	}
} 

public class JavaAPIDemo{
 public static void main(String[] args) throws Exception{
  String str=StringUtil.encode("www.mldn.cn");
  System.out.println(StringUtil.decode(str));
 }
 
}


关于怎么在java中使用Base64进行加密与解密问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI