Java 之 BASE64 加密解密

avatar 2018年02月24日12:11:04 7 2985 views
博主分享免费Java教学视频,B站账号:Java刘哥

背景

在给邮件发送 URL 链接找回密码时,会发送一个链接,像这样 http://localhost:8080/resetpass?sid=c1b55b980db4eb74a4264a92d53cd953&account=saysky 验证原理就是,当用户点击链接,然后请求 控制器里的 resetpass 方法,获得 sid(密钥) 和 account(用户名) 两个参数。根据用户名去数据库中的 “邮件找回密码” 表(mail_retrieve)里寻找记录,获得 mailRetrieve 对象,然后比较 参数中的 sid 和 mailRetrieve.getSid() 即可,当然也可以加一个outtimes 超时时间 字段。 如上链接,sid 是经过 MD5 加密,并且无需解密,只需要比较参数dis和数据库sid是否相等,而account 用户名一定要传过去,目前是直接明文显示,感觉不是特别好,所以这里需要给 accout 也加密一下比较好。然后在 控制器里接受参数的时候,然后在解密即可。 目标是,无需太复杂,肉眼无法识别即可,但求效率高。  

BASE64 加密解码

代码如下
  1. package com.liuyanzhao.chuyun.util;
  2. import sun.misc.BASE64Decoder;
  3. import sun.misc.BASE64Encoder;
  4. import java.io.UnsupportedEncodingException;
  5. /**
  6.  * @author 言曌
  7.  * @date 2018/2/24 上午11:45
  8.  */
  9. public class Base64Util {
  10.     /**
  11.      * 加密
  12.      * @param str
  13.      * @return
  14.      */
  15.     @SuppressWarnings("restriction")
  16.     public static String encode(String str) {
  17.         byte[] b = null;
  18.         String s = null;
  19.         try {
  20.             b = str.getBytes("utf-8");
  21.         } catch (UnsupportedEncodingException e) {
  22.             e.printStackTrace();
  23.         }
  24.         if (b != null) {
  25.             s = new BASE64Encoder().encode(b);
  26.         }
  27.         return s;
  28.     }
  29.     /**
  30.      * 解密
  31.      * @param s
  32.      * @return
  33.      */
  34.     @SuppressWarnings("restriction")
  35.     public static String decode(String s) {
  36.         byte[] b = null;
  37.         String result = null;
  38.         if (s != null) {
  39.             BASE64Decoder decoder = new BASE64Decoder();
  40.             try {
  41.                 b = decoder.decodeBuffer(s);
  42.                 result = new String(b, "utf-8");
  43.             } catch (Exception e) {
  44.                 e.printStackTrace();
  45.             }
  46.         }
  47.         return result;
  48.     }
  49.     public static void main(String args[]) {
  50.         Long startTime = System.currentTimeMillis();
  51.         String rawString = "loveluoqi";
  52.         String encodedString = encode(rawString);
  53.         String decodedString = decode(encodedString);
  54.         System.out.println(rawString);
  55.         System.out.println(encodedString);
  56.         System.out.println(decodedString);
  57.         Long endTime = System.currentTimeMillis();
  58.         System.out.println("总共耗时毫秒数:" + (endTime - startTime));
  59.     }
  60. }
  运行结果如下     本文链接:https://liuyanzhao.com/7578.html
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:1   待审核评论数:0
  1. avatar 哈哈哈

    厉害呀