程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Java 加解密 AES DES TripleDes,aestripledes

Java 加解密 AES DES TripleDes,aestripledes

編輯:JAVA綜合教程

Java 加解密 AES DES TripleDes,aestripledes


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); } }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved