java加解密

加解密方法

package com.my.srv.core;

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidParameterException;
import java.security.MessageDigest;
import java.security.SecureRandom;


/**
 * @author Jim
 */
public class EncryptTool {
    private static final String MD5 = "md5";
    private static final String SHA1 = "sha1";
    private static final String HmacMD5 = "HmacMD5";
    private static final String HmacSHA1 = "HmacSHA1";
    private static final String DES = "DES";
    private static final String AES = "AES";

    /**
     * 编码格式;默认使用uft-8
     */
    private String charset = "utf-8";
    /**
     * DES
     */
    private int keySizeDes = 0;
    /**
     * AES
     */
    private int keySizeAes = 128;

    private static EncryptTool self;

    private EncryptTool() {
        //单例
    }

    //双重锁
    public static EncryptTool getInstance() {
        if (self == null) {
            synchronized (EncryptTool.class) {
                if (self == null) {
                    self = new EncryptTool();
                }
            }
        }
        return self;
    }

    /**
     * 使用MessageDigest进行单向加密(无密码)
     *
     * @param res       被加密的文本
     * @param algorithm 加密算法名称
     * @return
     */
    private String messageDigest(String res, String algorithm) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset);
            return base64(md.digest(resBytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 使用KeyGenerator进行单向/双向加密(可设密码)
     *
     * @param res       被加密的原文
     * @param algorithm 加密使用的算法名称
     * @param key       加密使用的秘钥
     * @return
     */
    private String keyGeneratorMac(String res, String algorithm, String key) {
        try {
            SecretKey sk = null;
            if (key == null) {
                KeyGenerator kg = KeyGenerator.getInstance(algorithm);
                sk = kg.generateKey();
            } else {
                byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
                sk = new SecretKeySpec(keyBytes, algorithm);
            }
            Mac mac = Mac.getInstance(algorithm);
            mac.init(sk);
            byte[] result = mac.doFinal(res.getBytes());
            return base64(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 使用KeyGenerator双向加密,DES/AES,注意这里转化为字符串的时候是将2进制转为16进制格式的字符串,不是直接转,因为会出错
     *
     * @param res       加密的原文
     * @param algorithm 加密使用的算法名称
     * @param key       加密的秘钥
     * @param keySize
     * @param isEncode
     * @return
     */
    private String keyGeneratorES(String res, String algorithm, String key, int keySize, boolean isEncode) {
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);
            if (keySize == 0) {
                byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
                random.setSeed(keyBytes);
                keyGen.init(random);
            } else if (key == null) {
                keyGen.init(keySize);
            } else {
                byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
                random.setSeed(keyBytes);
                keyGen.init(keySize, random);
            }
            SecretKey sk = keyGen.generateKey();
            SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
            Cipher cipher = Cipher.getInstance(algorithm);
            if (isEncode) {
                cipher.init(Cipher.ENCRYPT_MODE, sks);
                byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset);
                return parseByte2HexStr(cipher.doFinal(resBytes));
            } else {
                cipher.init(Cipher.DECRYPT_MODE, sks);
                return new String(cipher.doFinal(parseHexStr2Byte(res)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String base64(byte[] res) {
        return Base64.getEncoder().encodeToString(res);
    }

    /**
     * 将二进制转换成16进制
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * md5加密算法进行加密(不可逆)
     *
     * @param res 需要加密的原文
     * @return
     */
    public String md5(String res) {
        return messageDigest(res, MD5);
    }

    /**
     * md5加密算法进行加密(不可逆)
     *
     * @param res 需要加密的原文
     * @param key 秘钥
     * @return
     */
    public String md5(String res, String key) {
        return keyGeneratorMac(res, HmacMD5, key);
    }

    /**
     * 使用SHA1加密算法进行加密(不可逆)
     *
     * @param res 需要加密的原文
     * @return
     */
    public String sha1(String res) {
        return messageDigest(res, SHA1);
    }

    /**
     * 使用SHA1加密算法进行加密(不可逆)
     *
     * @param res 需要加密的原文
     * @param key 秘钥
     * @return
     */
    public String sha1(String res, String key) {
        return keyGeneratorMac(res, HmacSHA1, key);
    }

    /**
     * 使用DES加密算法进行加密(可逆)
     *
     * @param res 需要加密的原文
     * @param key 秘钥
     * @return
     */
    public String desEncode(String res, String key) {
        return changePosition(keyGeneratorES(res, DES, key, keySizeDes, true));
    }

    /**
     * 对使用DES加密算法的密文进行解密(可逆)
     *
     * @param res 需要解密的密文
     * @param key 秘钥
     * @return
     */
    public String desDecode(String res, String key) {
        res = changePosition(res);
        return keyGeneratorES(res, DES, key, keySizeDes, false);
    }

    /**
     * 使用AES加密算法经行加密(可逆)
     *
     * @param res 需要加密的密文
     * @param key 秘钥
     * @return
     */
    public String aesEncode(String res, String key) {
        return keyGeneratorES(res, AES, key, keySizeAes, true);
    }

    /**
     * 对使用AES加密算法的密文进行解密
     *
     * @param res 需要解密的密文
     * @param key 秘钥
     * @return
     */
    public String aesDecode(String res, String key) {
        return keyGeneratorES(res, AES, key, keySizeAes, false);
    }

    /**
     * 使用异或进行加密
     *
     * @param res 需要加密的密文
     * @param key 秘钥
     * @return
     */
    public String xorEncode(String res, String key) {
        byte[] bs = res.getBytes();
        for (int i = 0; i < bs.length; i++) {
            bs[i] = (byte) ((bs[i]) ^ key.hashCode());
        }
        return parseByte2HexStr(bs);
    }

    /**
     * 使用异或进行解密
     *
     * @param res 需要解密的密文
     * @param key 秘钥
     * @return
     */
    public String xorDecode(String res, String key) {
        byte[] bs = parseHexStr2Byte(res);
        for (int i = 0; i < bs.length; i++) {
            bs[i] = (byte) ((bs[i]) ^ key.hashCode());
        }
        return new String(bs);
    }

    /**
     * 直接使用异或(第一调用加密,第二次调用解密)
     *
     * @param res 密文
     * @param key 秘钥
     * @return
     */
    public int xor(int res, String key) {
        return res ^ key.hashCode();
    }

    /**
     * 使用Base64进行加密
     *
     * @param res 密文
     * @return
     */
    public String base64Encode(String res) {
        return Base64.getEncoder().encodeToString(res.getBytes());
    }

    /**
     * 使用Base64进行解密
     *
     * @param res
     * @return
     */
    public String base64Decode(String res) {
        return new String(Base64.getDecoder().decode(res));
    }

    private String changePosition(String src) {
        final int minLength = 4;
        char[] chars = src.toCharArray();
        int len = src.length();
        if (len < minLength) {
            throw new InvalidParameterException("The string length must greater than 4.");
        }
        char temp = chars[1];
        chars[1] = chars[len - 2];
        chars[len - 2] = temp;
        temp = chars[3];
        chars[3] = chars[len - 4];
        chars[len - 4] = temp;
        return new String(chars);
    }

    public static void main(String[] args) {
        String src = "123456";
        String key = "be5e0323a9195ade5f56695ed9f2eb6b036f3e6417115d0cbe2fb9d74d8740406838dc84f152014b39a241" +
                "4fb3530a40bc028a9e87642bd03cf5c36a1f70801e";
        EncryptTool et = EncryptTool.getInstance();
        String out = et.desEncode(src, key);
        System.out.println(out);
        out = "61A61413CEF9C9F4";
        System.out.println(et.desDecode(out, key));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值