Java温故而知新-Base64加密解密

104 篇文章 1 订阅

Base64加密解密

import java.util.Base64;

public class YootkDemo {    // 李兴华编程训练营:yootk.ke.qq.com
    public static void main(String[] args) throws Exception {
        String message = "www.yootk.com" ; // 原始数据
        Base64.Encoder encoder = Base64.getEncoder();   // 加密工具类
        byte[] encodeData = encoder.encode(message.getBytes()) ; // 对数据进行加密处理
        System.out.println("【加密后的数据】" + new String(encodeData));
        Base64.Decoder decoder = Base64.getDecoder(); // 解密工具类
        byte[] decodeData = decoder.decode(encodeData);// 字节数组进行解密
        System.out.println("【解密后的数据】" + new String(decodeData));
    }
}

在这里插入图片描述

封装一个加密解决的工具类

package com.yootk.util;

import java.util.Base64;

public class PasswordUtil { // 定义一个密码的加密处理类
    private static final int REPEAT = 5 ; // 重复加密5次
    private static final String SALT = "edu.yootk.com" ; // 追加操作盐值
    private PasswordUtil() {}   // 该类的方法为static方法
    public static String encrypt(String str) {
        String encodeData = "{" + SALT + "}" + str ; // 处理要加密的数据
        Base64.Encoder encoder = Base64.getEncoder();
        for (int x = 0 ; x < REPEAT ; x ++) {   // 执行多次编码操作
            encodeData = encoder.encodeToString(encodeData.getBytes()) ; // 加密操作
        }
        return encodeData ;
    }
    public static String decrypt(String str) {
        Base64.Decoder decoder = Base64.getDecoder();// 获得解密类
        byte data [] = str.getBytes() ; // 根据字节数组进行解密操作
        for (int x = 0 ; x < REPEAT ; x ++) {
            data = decoder.decode(data) ; // 多次解密
        }
        String decodeData = new String(data) ; // 包含有盐值的数据
        return decodeData.substring(("{" + SALT + "}").length()) ;
    }
}
package com.yootk.demo;

import com.yootk.util.PasswordUtil;

public class YootkDemo {    // 李兴华编程训练营:yootk.ke.qq.com
    public static void main(String[] args) throws Exception {
        String message = "www.yootk.com" ; // 原始数据
        System.out.println(PasswordUtil.encrypt(message));
        System.out.println(PasswordUtil.decrypt(PasswordUtil.encrypt(message)));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值