介绍
怎么在java中使用Base64进行加密与解密?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
Base64加密与解密操作
package cn.mldn.demo; import java.util.Base64; public class  JavaAPIDemo { public 才能;static  void main (String [], args), throws 异常{ ,,String 味精=皐ww.mldn.cn",,,,//原始内容 ,,String encMsg=new 字符串(Base64.getEncoder () .encode (msg.getBytes()));//数据加密 ,,System.out.println (encMsg);,,,,//输出密文 ,,String oldMsg=new 字符串(Base64.getDecoder () .decode (encMsg)),,//数据解密 ,,System.out.println (oldMsg);,//输出明文 ,,} }
程序执行结果:
引用>
d3d3Lm1sZG4uY24=(密文)
www.mldn.cn(明文)本程序直接利用Base64提供的方法获取了Base64.Encoder与Base64.Decoder实例化对象,并且对原始数据进行了加密与解密处理。但需要注意的是,由于Base64属于JDK的原始实现,所以单纯地加密是不安全的,此时为了获取更加安全的数据加密操作,可以利用盐值(盐),自定义格式以及多次加密的方式来保证项目中的数据安全。
基于Base64定义复杂加密与解密操作
package cn.mldn.demo; import java.util.Base64; class StringUtil { private static  final String 盐=癿ldnjava",,//公共的盐值 private static  final int 重复=5;,,//加密次数 public static  String 编码(String str),{//才能加密处理 String temp=str +“{“+盐+“}”;//盐值对外不公布 byte 数据[]=temp.getBytes ();//将字符串变为字节数组 (int x=0; x<重复;x + +) data=https://www.yisu.com/zixun/Base64.getEncoder () .encode(数据);//重复加密 返回新字符串(数据);//返回加密后的内容 } 公共静态字符串解码(String str) { 字节数据[]=str.getBytes ();//获取加密内容 (int x=0; x <重复;x + +) data=Base64.getDecoder () .decode(数据);//多次解密 返回新字符串(数据).replaceAll (“//{//w +//} ", " ");//删除盐值格式 } } 公开课JavaAPIDemo { 公共静态void main (String [] args){抛出异常 字符串str=StringUtil.encode (“www.mldn.cn”); System.out.println (StringUtil.decode (str)); } }引用>
怎么在java中使用Base64进行加密与解密