MD5、AES 算法加密、解密

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


/**
 * @Author mxy
 * @Desc 加密\解密工具类
 * 密钥(密码)长度只能为16, 24, 32 位长度
 * 加密过程: 加密-Base64编码
 * 解密过程: Base64解码-解密
 */
public class encryptUtils {

    /** 加密模式 */
    private static final String TRANS_FORMATION = "AES/ECB/PKCS5Padding";
    /** 加密算法 */
    private static final String ALGORITHM = "AES";
    /** 字符编解码 */
    private static final String CHARSET_NAME = "UTF-8";


    /**
     * MD5加密
     *
     * @param data
     * @return
     */
    public static String encryptByMD5(String data) {
        String reMd5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(data.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer();
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            reMd5 = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return reMd5.toUpperCase();
    }


    /**
     * AES 加密
     *
     * @param value       原始字符串
     * @return base64     编码后的加密字符串
     * @throws Exception  编码异常
     */
    public static String encryptByAES(String password, String value) throws Exception {
        SecretKeySpec aesKey = new SecretKeySpec(password.getBytes(Charset.forName(CHARSET_NAME)), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANS_FORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName(CHARSET_NAME)));

        return Base64.getEncoder().encodeToString(encrypted);
    }


    /**
     * AES 解密
     *
     * @param value base64 编码后的加密字符串
     * @return base64      解码后的原始字符串
     * @throws Exception   解码异常
     */
    public static String decryptByAES(String password, String value) throws Exception {
        byte[] decode = Base64.getDecoder().decode(value.getBytes(StandardCharsets.UTF_8));

        SecretKeySpec aesKey = new SecretKeySpec(password.getBytes(Charset.forName(CHARSET_NAME)), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANS_FORMATION);
        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        return new String(cipher.doFinal(decode));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值