<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    ice world

    There is nothing too difficult if you put your heart into it.
    posts - 104, comments - 103, trackbacks - 0, articles - 0

    Java AES文件加解密

    Posted on 2012-05-19 13:43 IceWee 閱讀(11861) 評論(2)  編輯  收藏 所屬分類: Java 、加解密
    之前寫了DES加解密,AES幾乎與之相同,不同的是底層key的位數而已,不過這些對于我們使用者都是透明的。

    AESUtils.java
    package demo.security;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.security.Key;
    import java.security.SecureRandom;

    import javax.crypto.Cipher;
    import javax.crypto.CipherInputStream;
    import javax.crypto.CipherOutputStream;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    /**
     * <p>
     * AES加密解密工具包
     * </p>
     * 
     * 
    @author IceWee
     * @date 2012-5-18
     * 
    @version 1.0
     
    */

    public class AESUtils {

        
    private static final String ALGORITHM = "AES";
        
    private static final int KEY_SIZE = 128;
        
    private static final int CACHE_SIZE = 1024;
        
        
    /**
         * <p>
         * 生成隨機密鑰
         * </p>
         * 
         * 
    @return
         * 
    @throws Exception
         
    */

        
    public static String getSecretKey() throws Exception {
            
    return getSecretKey(null);
        }

        
        
    /**
         * <p>
         * 生成密鑰
         * </p>
         * 
         * 
    @param seed 密鑰種子
         * 
    @return
         * 
    @throws Exception
         
    */

        
    public static String getSecretKey(String seed) throws Exception {
            KeyGenerator keyGenerator 
    = KeyGenerator.getInstance(ALGORITHM);
            SecureRandom secureRandom;
            
    if (seed != null && !"".equals(seed)) {
                secureRandom 
    = new SecureRandom(seed.getBytes());
            }
     else {
                secureRandom 
    = new SecureRandom();
            }

            keyGenerator.init(KEY_SIZE, secureRandom); 
            SecretKey secretKey 
    = keyGenerator.generateKey(); 
            
    return Base64Utils.encode(secretKey.getEncoded());
        }

        
        
    /**
         * <p>
         * 加密
         * </p>
         * 
         * 
    @param data
         * 
    @param key
         * 
    @return
         * 
    @throws Exception
         
    */

        
    public static byte[] encrypt(byte[] data, String key) throws Exception {
            Key k 
    = toKey(Base64Utils.decode(key));
            
    byte[] raw = k.getEncoded(); 
            SecretKeySpec secretKeySpec 
    = new SecretKeySpec(raw, ALGORITHM); 
            Cipher cipher 
    = Cipher.getInstance(ALGORITHM); 
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            
    return cipher.doFinal(data);
        }

        
        
    /**
         * <p>
         * 文件加密
         * </p>
         * 
         * 
    @param key
         * 
    @param sourceFilePath
         * 
    @param destFilePath
         * 
    @throws Exception
         
    */

        
    public static void encryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {
            File sourceFile 
    = new File(sourceFilePath);
            File destFile 
    = new File(destFilePath); 
            
    if (sourceFile.exists() && sourceFile.isFile()) {
                
    if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }

                destFile.createNewFile();
                InputStream in 
    = new FileInputStream(sourceFile);
                OutputStream out 
    = new FileOutputStream(destFile);
                Key k 
    = toKey(Base64Utils.decode(key));
                
    byte[] raw = k.getEncoded(); 
                SecretKeySpec secretKeySpec 
    = new SecretKeySpec(raw, ALGORITHM); 
                Cipher cipher 
    = Cipher.getInstance(ALGORITHM); 
                cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
                CipherInputStream cin 
    = new CipherInputStream(in, cipher);
                
    byte[] cache = new byte[CACHE_SIZE];
                
    int nRead = 0;
                
    while ((nRead = cin.read(cache)) != -1{
                    out.write(cache, 
    0, nRead);
                    out.flush();
                }

                out.close();
                cin.close();
                in.close();
            }

        }

        
        
    /**
         * <p>
         * 解密
         * </p>
         * 
         * 
    @param data
         * 
    @param key
         * 
    @return
         * 
    @throws Exception
         
    */

        
    public static byte[] decrypt(byte[] data, String key) throws Exception {
            Key k 
    = toKey(Base64Utils.decode(key));
            
    byte[] raw = k.getEncoded(); 
            SecretKeySpec secretKeySpec 
    = new SecretKeySpec(raw, ALGORITHM); 
            Cipher cipher 
    = Cipher.getInstance(ALGORITHM); 
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            
    return cipher.doFinal(data);
        }

        
        
    /**
         * <p>
         * 文件解密
         * </p>
         * 
         * 
    @param key
         * 
    @param sourceFilePath
         * 
    @param destFilePath
         * 
    @throws Exception
         
    */

        
    public static void decryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {
            File sourceFile 
    = new File(sourceFilePath);
            File destFile 
    = new File(destFilePath); 
            
    if (sourceFile.exists() && sourceFile.isFile()) {
                
    if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }

                destFile.createNewFile();
                FileInputStream in 
    = new FileInputStream(sourceFile);
                FileOutputStream out 
    = new FileOutputStream(destFile);
                Key k 
    = toKey(Base64Utils.decode(key));
                
    byte[] raw = k.getEncoded(); 
                SecretKeySpec secretKeySpec 
    = new SecretKeySpec(raw, ALGORITHM); 
                Cipher cipher 
    = Cipher.getInstance(ALGORITHM); 
                cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
                CipherOutputStream cout 
    = new CipherOutputStream(out, cipher);
                
    byte[] cache = new byte[CACHE_SIZE];
                
    int nRead = 0;
                
    while ((nRead = in.read(cache)) != -1{
                    cout.write(cache, 
    0, nRead);
                    cout.flush();
                }

                cout.close();
                out.close();
                in.close();
            }

        }

        
        
    /**
         * <p>
         * 轉換密鑰
         * </p>
         * 
         * 
    @param key
         * 
    @return
         * 
    @throws Exception
         
    */

        
    private static Key toKey(byte[] key) throws Exception {
            SecretKey secretKey 
    = new SecretKeySpec(key, ALGORITHM);
            
    return secretKey;
        }

        
    }



    Base64Utils.java(依賴javabase64-1.3.1.jar)
    package demo.security;

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;

    import it.sauronsoftware.base64.Base64;

    /**
    * <p>
    * BASE64編碼解碼工具包
    * </p>
    * <p>
    * 依賴javabase64-1.3.1.jar
    * </p>
    *
    *
    @author IceWee
    * @date 2012-5-19
    *
    @version 1.0
    */

    public class Base64Utils {

       
    /**
         * 文件讀取緩沖區大小
        
    */

       
    private static final int CACHE_SIZE = 1024;
       
       
    /**
         * <p>
         * BASE64字符串解碼為二進制數據
         * </p>
         *
         *
    @param base64
         *
    @return
         *
    @throws Exception
        
    */

       
    public static byte[] decode(String base64) throws Exception {
           
    return Base64.decode(base64.getBytes());
        }

       
       
    /**
         * <p>
         * 二進制數據編碼為BASE64字符串
         * </p>
         *
         *
    @param bytes
         *
    @return
         *
    @throws Exception
        
    */

       
    public static String encode(byte[] bytes) throws Exception {
           
    return new String(Base64.encode(bytes));
        }

       
       
    /**
         * <p>
         * 將文件編碼為BASE64字符串
         * </p>
         * <p>
         * 大文件慎用,可能會導致內存溢出
         * </p>
         *
         *
    @param filePath 文件絕對路徑
         *
    @return
         *
    @throws Exception
        
    */

       
    public static String encodeFile(String filePath) throws Exception {
           
    byte[] bytes = fileToByte(filePath);
           
    return encode(bytes);
        }

       
       
    /**
         * <p>
         * BASE64字符串轉回文件
         * </p>
         *
         *
    @param filePath 文件絕對路徑
         *
    @param base64 編碼字符串
         *
    @throws Exception
        
    */

       
    public static void decodeToFile(String filePath, String base64) throws Exception {
           
    byte[] bytes = decode(base64);
            byteArrayToFile(bytes, filePath);
        }

       
       
    /**
         * <p>
         * 文件轉換為二進制數組
         * </p>
         *
         *
    @param filePath 文件路徑
         *
    @return
         *
    @throws Exception
        
    */

       
    public static byte[] fileToByte(String filePath) throws Exception {
           
    byte[] data = new byte[0];
            File file
    = new File(filePath);
           
    if (file.exists()) {
                FileInputStream in
    = new FileInputStream(file);
                ByteArrayOutputStream out
    = new ByteArrayOutputStream(2048);
               
    byte[] cache = new byte[CACHE_SIZE];
               
    int nRead = 0;
               
    while ((nRead = in.read(cache)) != -1) {
                    out.write(cache,
    0, nRead);
                    out.flush();
                }

                out.close();
                in.close();
                data
    = out.toByteArray();
             }

           
    return data;
        }

       
       
    /**
         * <p>
         * 二進制數據寫文件
         * </p>
         *
         *
    @param bytes 二進制數據
         *
    @param filePath 文件生成目錄
        
    */

       
    public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
            InputStream in
    = new ByteArrayInputStream(bytes);  
            File destFile
    = new File(filePath);
           
    if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }

            destFile.createNewFile();
            OutputStream out
    = new FileOutputStream(destFile);
           
    byte[] cache = new byte[CACHE_SIZE];
           
    int nRead = 0;
           
    while ((nRead = in.read(cache)) != -1) {  
                out.write(cache,
    0, nRead);
                out.flush();
            }

            out.close();
            in.close();
        }

       
       
    }



    AESTester.java
    package demo.security;

    public class AESTester {
       
       
    static String key;
       
       
    static {
           
    try {
    key
    = AESUtils.getSecretKey();
            }
    catch (Exception e) {
                e.printStackTrace();
            }

        }


       
    public static void main(String[] args) throws Exception {
           
    long begin = System.currentTimeMillis();
            encryptFile();
            decryptFile();
            test();
           
    long end = System.currentTimeMillis();
            System.err.println(
    "耗時:" + (end-begin)/1000 + "");
        }

       
       
    static void encryptFile() throws Exception {
            String sourceFilePath
    = "D:/demo.mp4";
            String destFilePath
    = "D:/demo_encrypted.mp4";
            AESUtils.encryptFile(key, sourceFilePath, destFilePath);
        }

       
       
    static void decryptFile() throws Exception {
            String sourceFilePath
    = "D:/demo_encrypted.mp4";
            String destFilePath
    = "D:/demo_decrypted.mp4";
            AESUtils.decryptFile(key, sourceFilePath, destFilePath);
        }

       
       
    static void test() throws Exception {
            String source
    = "這是一行測試DES加密/解密的文字,你看完也等于沒看,是不是???!";
            System.err.println(
    "原文:\t" + source);
           
    byte[] inputData = source.getBytes();
            inputData
    = AESUtils.encrypt(inputData, key);
            System.err.println(
    "加密后:\t" + Base64Utils.encode(inputData));
           
    byte[] outputData = AESUtils.decrypt(inputData, key);
            String outputStr
    = new String(outputData);
            System.err.println(
    "解密后:\t" + outputStr);
        }


    }

    Feedback

    # re: Java AES文件加解密[未登錄]  回復  更多評論   

    2015-07-14 16:49 by xxx
    111

    # re: Java AES文件加解密  回復  更多評論   

    2015-10-10 14:30 by duhai
    666666666666666666666666666666666666666
    主站蜘蛛池模板: 老湿机一区午夜精品免费福利| 中文字幕无码亚洲欧洲日韩| 久久精品一本到99热免费| 国产成人精品日本亚洲网址| 国产一区二区视频免费| 永久在线观看免费视频 | 亚洲第一区精品观看| 97人妻精品全国免费视频| 亚洲中字慕日产2021| 亚洲国产成人久久综合碰| 久久精品免费一区二区| 黄色a三级三级三级免费看| 亚洲天堂在线播放| 凹凸精品视频分类国产品免费| 久久国产精品免费视频| 日韩精品亚洲专区在线影视| 婷婷亚洲久悠悠色悠在线播放| 国产福利免费观看| 四虎最新永久免费视频| 精品国产污污免费网站入口在线| 精品久久久久久亚洲精品| 亚洲热妇无码AV在线播放| 国产精品免费播放| xx视频在线永久免费观看| 久草免费福利在线| 亚洲精品乱码久久久久久蜜桃图片| 99人中文字幕亚洲区| 亚洲宅男天堂在线观看无病毒| 成年在线网站免费观看无广告| 午夜精品免费在线观看| 日本激情猛烈在线看免费观看 | 国产嫩草影院精品免费网址| 黄在线观看www免费看| 久久久精品国产亚洲成人满18免费网站| 亚洲免费观看在线视频| 亚洲国产精品久久久久久| 综合亚洲伊人午夜网| 免费人成网站7777视频| 成**人免费一级毛片| 免费99精品国产自在现线| 无人在线观看免费高清|