重温java知识(三十四、常用类库之七:Base64加密与解密)

  • 数据加密:public static Base64.Encoder getEncoder()。数据加密处理:public byte[] encoder(byte[] src);
  • 数据解密:public static Base64.Decoder getDecoder()。数据加密处理:public byte[] decoder(String src);

1、实现Base64加密与解密操作的例子:

package com.mydemo;

import java.util.Base64;

public class Base64Demo {

    public static void main(String[] args) {

        // 原文
        String msg = "Base64加密与解密的小例子";

        // 数据加密
        String enMsg = new String(Base64.getEncoder().encode(msg.getBytes()));
        System.out.println("密文:" + enMsg);

        // 数据解密
        String oldMsg = new String(Base64.getDecoder().decode(enMsg));
        System.out.println("明文:" + oldMsg);
    }
}
运行结果:
密文:QmFzZTY05Yqg5a+G5LiO6Kej5a+G55qE5bCP5L6L5a2Q
明文:Base64加密与解密的小例子

2、基于Base64定义复杂加密与解密操作的例子:

package com.mydemo;

import java.util.Base64;

public class Base64Demo {

    public static void main(String[] args) {

        // 原文
        String msg = "Base64加密与解密的小例子";

        // 数据加密
        String enMsg = StringUtil.encode(msg);
        System.out.println("密文:" + enMsg);

        // 数据解密
        String oldMsg = StringUtil.decode(enMsg);
        System.out.println("明文:" + oldMsg);
    }
}

/**
 * 定义一个字符串操作类,提供字符串的辅助处理功能
 */
class StringUtil {
    private static final String SALT = "mlgb";      // 公共的盐值
    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);                        // 返回加密后的内容
    }

    /**
     * 进行解密处理
     *
     * @param str 要解密的内容
     * @return 解密后的原始数据
     */
    public static String decode(String str) {
        byte data[] = str.getBytes();
        for (int i = 0; i < REPEAT; i++) {
            data = Base64.getDecoder().decode(data);
        }

        // 删除盐值格式
        return new String(data).replace("\\{\\w+\\}", "");
    }
}
运行结果:
密文:VmxaamVGSXlWbk5qUmxaWVZrVkZlRll4YUVkaWF6VllVbGhLVTJWc1drNVpWbFUwVFd4TmVWWnVSazlXTUZaNVZXNXdWazFYVGxaV1ZFWmFZVEExVWxSc1ZqTk5iRkpGVm0xb1RtSkZXbk5VVjNCSFpXeGtjVk5yZEZCVlZEQTU=
明文:Base64加密与解密的小例子{mlgb}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值