当前位置:   article > 正文

Java中Base64的简单使用_java base64.encode("":"")怎么用

java base64.encode("":"")怎么用

Base64 加密与解密

正常来讲加密基本上永远都要伴随着解密,所谓的加密或者是解密往往都要伴随着解密,所谓的加密或者是解密往往都需要有一些新的加密处理操作类,Base64 处理,在这个类里面有两个内部类:

  • Base64.Encoder:进行加密才能处理;

    • 加密处理:public byte[] encode(byte[] src);
  • Base64.Decoder:进行解密处理;

    • 解密处理: public byte[] decode(String src); 

实现加密解密操作

        String str = "~~~~~虫儿飞~~~~~";
        String encStr = new String(Base64.getEncoder().encode(str.getBytes()));
        System.out.println(encStr);
        String oldStr = new String(Base64.getDecoder().decode(encStr.getBytes()));
        System.out.println(oldStr);
  • 1
  • 2
  • 3
  • 4
  • 5

虽然 Base64 可以实现加密与解密的处理,但是其由于其是一个公版的算法,所以如果对其进行加密,最好的做法是使用盐值操作

        String salt = "byfjava";
        String str = "~~~~~虫儿飞~~~~~"+salt;
        String encStr = new String(Base64.getEncoder().encode(str.getBytes()));
        System.out.println(encStr);
        String oldStr = new String(Base64.getDecoder().decode(encStr.getBytes()));
        System.out.println(oldStr);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

即便有盐值处理,但加密效果并不完善,所以要用到多次加密

多次加密

class StringUtils {
    private static final String SALT = "byf666";// 公共的盐值
    private static final int REPEAT = 5;        // 加密次数 

    /**
     * 加密处理
     * @param str 要加密的字符串,需要与盐值整合
     * @return
     */
    public static String encode(String str) {
        String temp = str + SALT;
        byte data[] = temp.getBytes();
        for (int i = 0; i < REPEAT; i++) {
            data = Base64.getEncoder().encode(data);
        }
        return new String(data);
    }

    public static String decode(String str) {
        byte data[] = str.getBytes();
        for (int i = 0; i < REPEAT; i++) {
            data = Base64.getDecoder().decode(data);
        }
        String result = new String(data).replaceAll(SALT, "");
        return result;
    }
}

public class Base64Test {
    public static void main(String[] args) {
        String str = "~~~~~虫儿飞~~~~~";
        String encode = StringUtils.encode(str);// 加密
        System.out.println(encode);
		String decode = StringUtils.decode(encode);// 解密
        System.out.println(decode);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

最好的做法是使用 2-3 种加密程序,同时在找到一些完全不可解密的加密算法。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/881716?site
推荐阅读
相关标签
  

闽ICP备14008679号