AES加密解密

AES是一種對稱加密,簡單理解爲祕鑰只有一個,加密解密都用它,安全性不是很好java

package com.aisino.qysds.common.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;


public class AESUtil {

    private static final String charset = "UTF-8";
    private final static int length=128;
    private final static String base = "abcdefghijklmnopqrstuvwxyz0123456789"; 
    private static final String KEY_AES = "AES";
    
    /**
     * aes ECB 模式加密
     * @param encryptStr
     * @param decryptKey
     * @return
     */
    public static String encryptECB(String encryptStr, String decryptKey){
        try{
             return parseByte2HexStr(encrypt_ECB(encryptStr, decryptKey)); 
        }catch(Exception e) {
                return null;
        }
    }

    /**
     * aes ECB 模式解密
     * @param encryptStr
     * @param decryptKey
     * @return
     * @throws Exception
     */
    public static String decryptECB(String encryptStr, String decryptKey)throws Exception{
        return decrypt_ECB(parseHexStr2Byte(encryptStr), decryptKey);  
    }
    /**
     * 加密 ECB
     * @param content
     * 須要加密的內容
     * @param password
     * 加密密碼
     * @return
     */
    private static byte[] encrypt_ECB(String content, String encryptKey) throws Exception {
        try {
            Cipher aesECB = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), KEY_AES);
            aesECB.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = aesECB.doFinal(content.getBytes(charset));
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 解密 ECB
     * @param content 待解密內容
     * @param password 解密密鑰
     * @return
     */
    private static String decrypt_ECB(byte[] encryptBytes, String decryptKey) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 建立密碼器
            SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), KEY_AES);
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            //byte[] result = parseHexStr2Byte(content);
            return new String(cipher.doFinal(encryptBytes)); // 解密
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
        
    }
    
    
    
    /**
     * aes 默認加密
     * @param content
     * 須要加密的內容
     * @param password
     * 加密密碼
     * @return
     */
    private static byte[] encrypt(String content, String password) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); 
        secureRandom.setSeed(password.getBytes());
        kgen.init(length, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat,KEY_AES);
        Cipher cipher = Cipher.getInstance(KEY_AES);// 建立密碼器
        byte[] byteContent = content.getBytes(charset);
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return result; // 加密
    }


    /**
     * aes 默認解密
     * @param content 待解密內容
     * @param password 解密密鑰
     * @return
     */
    private static byte[] decrypt(byte[] content, String password) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); 
        secureRandom.setSeed(password.getBytes());
        kgen.init(length, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat,KEY_AES);
        Cipher cipher = Cipher.getInstance(KEY_AES);// 建立密碼器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(content);
        return result; // 加密
    }


    /**
     * aes 默認加密
     * @param content
     * @param password
     * @return
     */
    public static String encryptAES(String content, String password){
        try{
            byte[] encryptResult = encrypt(content, password);
            return encode(encryptResult);
        }catch(Exception e) {
                return null;
        }
    }

    /**
     * aes 默認解密
     * @param content
     * @param password
     * @return
     */
    
    public static String decryptAES(String content, String password){
        try{
            byte[] decryptResult = decrypt(decode(content.getBytes()), password);
            return new String(decryptResult,charset);
        }catch(Exception e) {
                return null;
        }
    }


    /**
     * 得到隨機數
     * @param len
     * @return
     */
    public static String randomStr(int len) {
        Random random = new Random();     
        StringBuffer sb = new StringBuffer();     
        for (int i = 0; i < len; i++) {     
            int number = random.nextInt(base.length());     
            sb.append(base.charAt(number));     
        }     
        return sb.toString();  
    }

    /**將二進制轉換成16進制 
     * @param buf 
     * @return 
     */  
    public static String parseByte2HexStr(byte buf[]) {  
            StringBuffer sb = new StringBuffer();  
            for (int i = 0; i < buf.length; i++) {  
                    String hex = Integer.toHexString(buf[i] & 0xFF);  
                    if (hex.length() == 1) {  
                            hex = '0' + hex;  
                    }  
                    sb.append(hex.toUpperCase());  
            }  
            return sb.toString();  
    } 
    
    /**將16進制轉換成2進制 
     * @param buf 
     * @return 
     */
    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;  
    }
    
    /**
     * 數據編碼爲BASE64字符串 轉爲 二進制
     * @param bytes
     * @return
     */
    public static byte[] decode(final byte[] bytes) {  
        return Base64.decodeBase64(bytes);  
    }  
    /** 
     * 二進制數據編碼爲BASE64字符串 
     * 
     * @param bytes 
     * @return 
     * @throws Exception 
     */  
    public static String encode(final byte[] bytes) {  
        return new String(Base64.encodeBase64(bytes));  
    }  
    /** 
     * 字符串轉換unicode 
     */  
    public static String string2Unicode(String string) {  
        StringBuffer unicode = new StringBuffer();  
        for (int i = 0; i < string.length(); i++) {  
            // 取出每個字符  
            char c = string.charAt(i);  
            // 轉換爲unicode  
            unicode.append("\\u" + Integer.toHexString(c));  
        }  
        return unicode.toString();  
    } 
    /** 
     * unicode 轉字符串 
     */  
    public static String unicode2String(String unicode) {  
        StringBuffer string = new StringBuffer();  
        String[] hex = unicode.split("\\\\u");  
        for (int i = 1; i < hex.length; i++) {  
            // 轉換出每個代碼點  
            int data = Integer.parseInt(hex[i], 16);  
            // 追加成string  
            string.append((char) data);  
        }  
        return string.toString();  
    } 
    
    public static void main(String[] args) throws Exception {
        String content ="1231";
        String key = "AAAAAAAAAAAAAAAA";
        // 加密
        System.out.println("加密前:"+content );
        String tt4 = encryptECB(content, key);
        System.out.println(new String(tt4));

        // 解密
        String d = decryptECB(tt4, key);
        System.out.println("解密後:"+ d);
    }
    
}

結果輸出apache

加密前:1231
15428541F01951FF4F0A2990535F2C81
解密後:1231
相關文章
相關標籤/搜索