前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java加解密AES、DES、TripleDES、MD5、SHA

Java加解密AES、DES、TripleDES、MD5、SHA

作者头像
WindWant
发布2020-09-11 10:59:20
2.1K0
发布2020-09-11 10:59:20
举报
文章被收录于专栏:后端码事后端码事

一、AES、DES、TripleDES

代码语言:javascript
复制
package xxx.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * Created by windwant on 2016/12/13.
 */
public class EncryptUtil {
    private static final Logger logger = LoggerFactory.getLogger(EncryptUtil.class);

    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String EMPTY_STR = "";
    private static final int AES_KEY_SIZE = 16;//256/192/128~32/24/16

    public static void main(String[] args) {
        String tempkey = "!@#$%^&*()_+";
        String ming = "at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_77]";

        long begin = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            String en = tripleDesEncrypt(ming, tempkey);
            String den = tripleDesDecrypt(en, tempkey);
        }
        long end = System.currentTimeMillis();
        System.out.println("TripleDES: " + (end - begin));
        System.out.println("TripleDES: " + (end - begin)/100000.0);

        begin = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            String en = desEncrypt(ming, tempkey);
            String den = desDecrypt(en, tempkey);
        }
        end = System.currentTimeMillis();
        System.out.println("DES: " + (end - begin));
        System.out.println("DES: " + (end - begin)/100000.0);

        begin = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            String en = aesEncrypt(ming, tempkey);
            String den = aesDecrypt(en, tempkey);
        }
        end = System.currentTimeMillis();
        System.out.println("AES: " + (end - begin));
        System.out.println("AES: " + (end - begin)/100000.0);
        /*
        100000次
        key: !@#$%^&*()_+
        src: at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_77]
        TripleDES: 3831
        TripleDES: 0.03831
        DES: 845
        DES: 0.00845
        AES: 888
        AES: 0.00888
        */
    }

    private static final String ENCRYPT = "AES";
    private static final String CIPHER = "AES/CBC/PKCS5Padding";

    /**
     * AES加密
     * @param key 加密密钥
     * @param src 加密内容
     * @return 返回BASE64密文
     */
    public static final String aesEncrypt(String src, String key) {
        if(key == null || src == null){
            return EMPTY_STR;
        }
        try {
            byte[] bs = getAESResult(key, src.getBytes(DEFAULT_CHARSET), Cipher.ENCRYPT_MODE);
            if (bs != null) {
                return Base64.getEncoder().encodeToString(bs);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return src;
    }

    /**
     * AES解密
     * @param key 解密密钥
     * @param src 解密内容
     * @return 明文
     */
    public static final String aesDecrypt(String src, String key) {
        if(key == null || src == null){
            return EMPTY_STR;
        }
        try {
            byte[] bs = getAESResult(key, Base64.getDecoder().decode(src.getBytes(DEFAULT_CHARSET)), Cipher.DECRYPT_MODE);
            if (bs != null) {
                return new String(bs, DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return src;
    }

    /**
     * AES加解密结果
     * @param key 密钥
     * @param textBytes 明文 密文 字节数组
     * @param encryptMode 加密 解密
     * @return
     */
    private static byte[] getAESResult(String key, byte[] textBytes, final int encryptMode)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, 
            IllegalBlockSizeException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
        Key newKey = new SecretKeySpec(buildCLenKey(key, AES_KEY_SIZE), ENCRYPT);
        Cipher cipher = Cipher.getInstance(ENCRYPT);
        cipher.init(encryptMode, newKey, new SecureRandom());
        return cipher.doFinal(textBytes);
    }


    //定义加密算法,有DES、DESede(3DES)
    private static final String ALGORITHM = "DESede";
    // 算法名称/加密模式/填充方式
    private static final String CIPHER_ALGORITHM_ECB = "DESede/ECB/PKCS5Padding";
    /**
     * TripleDES加密方法
     * @param src
     * @param key
     * @return BASE64
     */
    public static final String tripleDesEncrypt(String src, String key) {
        if(key == null || src == null){
            return EMPTY_STR;
        }
        try {
            byte[] des = getTripleDESResult(key, src.getBytes(), Cipher.ENCRYPT_MODE);
            if(des != null) {
                return Base64.getEncoder().encodeToString(des);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return src;
    }

    /**
    * TripleDES解密函数
    * @param src 密文的字节数组
    * @param key 密钥
    * @return String 明文
            */
    public static final String tripleDesDecrypt(String src, String key) {
        if(key == null || src == null){
            return EMPTY_STR;
        }
        try {
            byte[] srcb =  Base64.getDecoder().decode(src);
            byte[] des = getTripleDESResult(key, srcb, Cipher.DECRYPT_MODE);
            return new String(des, DEFAULT_CHARSET);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return src;
    }

    /**
     * TripleDES加解密结果
     * @param key 密钥
     * @param textBytes 明文 密文 字节数组
     * @param encryptMode 加密 解密
     * @return
     */
    private static byte[] getTripleDESResult(String key, byte[] textBytes, final int encryptMode) 
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
            IllegalBlockSizeException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
        Key newKey = new SecretKeySpec(buildCLenKey(key, 24), ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB);
        cipher.init(encryptMode, newKey, new SecureRandom());
        return cipher.doFinal(textBytes);
    }

    /**
     * 根据字符串生成密钥字节数组
     * @param keyStr 密钥字符串
     * @param lgn 密钥长度
     * @return 长度密钥字节数组
     * @throws UnsupportedEncodingException
     */
    private static byte[] buildCLenKey(String keyStr, int lgn) throws UnsupportedEncodingException {
        byte[] key = new byte[lgn];    //声明一个24位的字节数组,默认里面都是0
        byte[] temp = keyStr.getBytes("UTF-8");    //将字符串转成字节数组

        ///执行数组拷贝
        if (key.length > temp.length) {
            //如果temp不够24位,则拷贝temp数组整个长度的内容到key数组中
            System.arraycopy(temp, 0, key, 0, temp.length);
        } else {
            //如果temp大于24位,则拷贝temp数组24个长度的内容到key数组中
            System.arraycopy(temp, 0, key, 0, key.length);
        }
        return key;
    }


    private static final String DES_ALGORITHM = "DES";
    public static final String DES_CIPHER_ALGORITHM = "DES";
    /**
    * DES 加密方法
    * @param src
    * @param key
    * @return BASE64
    */
    public static final String desEncrypt(String src, String key) {
        if(key == null || src == null){
            return EMPTY_STR;
        }
        try {
            byte[] des = getDESResult(key, src.getBytes(), Cipher.ENCRYPT_MODE);
            if(des != null) {
                return Base64.getEncoder().encodeToString(des);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return src;
    }

    /**
     * DES解密函数
     * @param src 密文的字节数组
     * @param key 密钥
     * @return String 明文
     */
    public static final String desDecrypt(String src, String key) {
        if(key == null || src == null){
            return EMPTY_STR;
        }
        try {
            byte[] srcb = Base64.getDecoder().decode(src);
            byte[] des = getDESResult(key, srcb, Cipher.DECRYPT_MODE);
            return new String(des, DEFAULT_CHARSET);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return src;
    }

    private static byte[] getDESResult(String key, byte[] textBytes, final int encryptMode) 
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, 
            IllegalBlockSizeException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
        Key newKey = new SecretKeySpec(buildCLenKey(key, 8), DES_ALGORITHM);
        Cipher cipher = Cipher.getInstance(DES_CIPHER_ALGORITHM);
        cipher.init(encryptMode, newKey, new SecureRandom());
        return cipher.doFinal(textBytes);
    }
}

二、散列MD5、SHA

代码语言:javascript
复制
package xxx.common.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 消息摘要 散列
 * Created by windwant on 2016/12/14.
 */
public class MessageDigestUtil {

    public static void main(String[] args) {
        System.out.println(md5("lilei"));
        System.out.println(sha("lilei"));
    }

    private static String md5(String data){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(data.getBytes());
            return  new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String sha(String data){
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(data.getBytes());
            return  new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-12-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、AES、DES、TripleDES
  • 二、散列MD5、SHA
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档