Java 加解密 AES DES TripleDes,aestripledes

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.