[Java 實現AES加密解密]

今天同窗請教我這個問題,被坑了次……html

實現的功能是2個Java類:一個讀取源文件生成加密文件,另外一個類讀取加密文件來解密。java

整個過程其實很簡單,java有AES的工具包,設好祕鑰,設好輸入內容,就獲得加密結果和解密結果了。算法

然而百度搜AES加密,最早跳出的必須是這個博客 http://www.cnblogs.com/freeliver54/archive/2011/10/08/2202136.htmldom

後來才發現下面的評論:工具

「kgen.init(128, new SecureRandom(password.getBytes()));
我但是被你坑慘了 啊!!!!
你用你的加密算法加密一段字符,一週之後,你再用你的解密方法,看看可否解密!!!!!!
等你回答!!!!!」 加密

簡單的說就是這貨給本來約定祕鑰A再利用時間種子隨機成16位做爲加密祕鑰B(目的應該是爲了避開16位的限制)…雖然約定祕鑰都是A,WINS能跑是由於短期獲得祕鑰B可能同樣,但你長時間隨機出來的加密祕鑰B就確定不同了,這樣AES解密就解不開了。。。spa

因此這個方法是錯誤的。。(並且裏面的UTF-8也不對吧,遇到GBK的就跪了)code

一種解決辦法是,對把A隨機成B的種子變成固定值,這樣每次獲得B就同樣了。並且解決了16位限制的問題。orm

 

public static byte[] encrypt(String content, String password) {
        try {
            
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random=SecureRandom.getInstance("SHA1PRNG");//加解密保持同個隨機種子
            random.setSeed(password.getBytes());
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 建立密碼器
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content.getBytes());
            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();
        }
        return null;
    }

 

 

看網上一個代碼,寫的比較精簡,祕鑰必須是16位的,如須要任意位,能夠按上面說的加個僞隨機,但不要像那位博主同樣拿時間作種子了。htm

import javax.crypto.Cipher;  
import javax.crypto.spec.SecretKeySpec;  
import java.io.*; 

/** 
 * This program generates a AES key, retrieves its raw bytes, and then 
 * reinstantiates a AES key from the key bytes. The reinstantiated key is used 
 * to initialize a AES cipher for encryption and decryption. 
 */  
  
public class AES {  
      
    private static final String AES = "AES";  
  
    private static final String CRYPT_KEY = "YUUAtestYUUAtest";  
  
    /** 
     * 加密 
     *  
     * @param encryptStr 
     * @return 
     */  
    public static byte[] encrypt(byte[] src, String key) throws Exception {  
        Cipher cipher = Cipher.getInstance(AES);  
        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);  
        cipher.init(Cipher.ENCRYPT_MODE, securekey);//設置密鑰和加密形式  
        return cipher.doFinal(src);  
    }  
  
    /** 
     * 解密 
     *  
     * @param decryptStr 
     * @return 
     * @throws Exception 
     */  
    public static byte[] decrypt(byte[] src, String key)  throws Exception  {  
        Cipher cipher = Cipher.getInstance(AES);  
        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);//設置加密Key  
        cipher.init(Cipher.DECRYPT_MODE, securekey);//設置密鑰和解密形式  
        return cipher.doFinal(src);  
    }  
      
    /** 
     * 二行制轉十六進制字符串 
     *  
     * @param b 
     * @return 
     */  
    public static String byte2hex(byte[] b) {  
        String hs = "";  
        String stmp = "";  
        for (int n = 0; n < b.length; n++) {  
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
            if (stmp.length() == 1)  
                hs = hs + "0" + stmp;  
            else  
                hs = hs + stmp;  
        }  
        return hs.toUpperCase();  
    }  
  
    public static byte[] hex2byte(byte[] b) {  
        if ((b.length % 2) != 0)  
            throw new IllegalArgumentException("長度不是偶數");  
        byte[] b2 = new byte[b.length / 2];  
        for (int n = 0; n < b.length; n += 2) {  
            String item = new String(b, n, 2);  
            b2[n / 2] = (byte) Integer.parseInt(item, 16);  
        }  
        return b2;  
    }  
      
    /** 
     * 解密 
     *  
     * @param data 
     * @return 
     * @throws Exception 
     */  
    public final static String decrypt(String data) {  
        try {  
            return new String(decrypt(hex2byte(data.getBytes()),  
                    CRYPT_KEY));  
        } catch (Exception e) {  
        }  
        return null;  
    }  
  
    /** 
     * 加密 
     *  
     * @param data 
     * @return 
     * @throws Exception 
     */  
    public final static String encrypt(String data) {  
        try {  
            return byte2hex(encrypt(data.getBytes(), CRYPT_KEY));  
        } catch (Exception e) {  
        }  
        return null;  
    }  
      
    public static String fromFile(String dir){
        String result ="";
        try{
            FileReader fr = new FileReader(dir);
            BufferedReader br = new BufferedReader(fr);
            String s=br.readLine();
            while(s!=null){
                result += s;
                s=br.readLine();
            }
        }
        catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
        
        return result;
    }

    public static void toFile(String s,String dir){
        try{
            File f = new File(dir);
            FileWriter fw = new FileWriter(f);
            fw.write(s);
            //System.out.println(s); 
            fw.close();
        }
        catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }            
    }
    public static void main(String[] args) {  
        String ID = "test";
        System.out.println("original string is:"+ID);  
        String idEncrypt = encrypt(ID);  
        System.out.println("encode result is:"+idEncrypt);  
        String idDecrypt = decrypt(idEncrypt);  
        System.out.println("decode result is:"+idDecrypt); 
        /*如下同窗的要求
        String ID = fromFile("/Users/shen/Desktop/source.txt");  
        String idEncrypt = encrypt(ID); 
        toFile(idEncrypt,"/Users/shen/Desktop/code.txt");        
        System.out.println(idEncrypt);  
        String idDecrypt = decrypt(idEncrypt);  
        toFile(new String(idDecrypt),"/Users/shen/Desktop/des.txt");
        System.out.println(idDecrypt);  
        */
    }  
      
}  
相關文章
相關標籤/搜索