Java中Base64的简单使用

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);

虽然 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);

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

多次加密

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);
    }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值