Java、Android平臺通用的AES文件加密

貌似是上個周五(2016.12.23)支付寶新推出的AR紅包,LBS加圖像識別的另一個創新,這個新玩法還是挺新穎的,算是支付寶社交的一個高招。公司的小伙伴玩得不亦樂乎,我也玩了一把。這些不是重點,這兩天看博客發現有很多人開始放大招去破解了。送點福利: http://thunf.me/aliAR/ 破解思路大同小異,大都是對圖片進行簡單的處理,盡可能還原出與原圖相似度較高的圖片。

話歸正傳,這段時間項目上馬熱修復,經過一段時間的調研選型,技術方案塵埃落定,最終用了阿里開源的AndFix。因為是金融產品,對安全性有一定要求,公司的安全部門也會嚴格監管,所以最后確定了一套安全方案。具體執行落到了我的頭上。具體的熱修復集成和原理不在此文贅述。github或者網上大牛的博客已經非常詳細。安全方案中用到了幾個常見的加密算法,非對稱加密RSA,對稱加密AES,還有MD5校驗以及文件加殼,除了AES實現過程中略顯蛋疼,其他問題都不大。

按理說,后端應提供上傳頁面供我們上傳補丁包,加密過程也該由他們去實現,但為了省去后端的工作量,我們選擇了將自行實現加密過程,然后將經過加密處理的補丁包還有一個必要的信息文件一起部署到服務器。為了實現自動化,決定將加密過程用java代碼實現打成jar包,然后用腳本去執行等到加密后的補丁包。這樣加密過程在java平臺實現,而解密過程是在Android平臺實現。后來發現在java平臺經AES加密后的文件在Android平臺用同一套代碼解不開。原因是有某些api存在不兼容的情況。幾經掙扎,最后還是解決了,下面貼出這段代碼,就是一個簡單的工具類。

package hotfix;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

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

/**
 * Created by pengdongyuan491 on 16/11/15.
 */

public class AESHelper {
    public static final String VIPARA = "0102030405060708";  
    private static final String TAG = AESHelper.class.getSimpleName();

    /**
     * 初始化 AES Cipher
     *
     * @param sKey
     * @param cipherMode
     * @return
     */
    private static Cipher initAESCipher(String sKey, int cipherMode) {
        //創建Key gen
        KeyGenerator keyGenerator = null;
        Cipher cipher = null;
        try {
                 IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());  
                SecretKeySpec key = new SecretKeySpec(sKey.getBytes(), "AES");  
                cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
                cipher.init(cipherMode, key, zeroIv);  
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InvalidKeyException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return cipher;
    }


    /**
     * 對文件進行AES加密
     *
     * @param key
     * @param sourceFilePath
     * @param destFilePath
     * @return
     */
    public static File encryptFile(String key, String sourceFilePath, String destFilePath) {
        System.out.printf(sourceFilePath);
        FileInputStream in = null;
        FileOutputStream out = null;
        File destFile = null;
        File sourceFile = null;
        try {
            sourceFile = new File(sourceFilePath);

            System.out.printf( sourceFilePath + "---" + sourceFile.getAbsolutePath());
            destFile = new File(destFilePath);
            if (sourceFile.exists() && sourceFile.isFile()) {
                if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }
                destFile.createNewFile();
                in = new FileInputStream(sourceFile);
                out = new FileOutputStream(destFile);
                Cipher cipher = initAESCipher(key, Cipher.ENCRYPT_MODE);
                //以加密流寫入文件
                CipherInputStream cipherInputStream = new CipherInputStream(in, cipher);
                byte[] cache = new byte[1024];
                int nRead = 0;
                while ((nRead = cipherInputStream.read(cache)) != -1) {
                    out.write(cache, 0, nRead);
                       out.flush();
                }
                cipherInputStream.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        return destFile;
    }


    /**
     * AES方式解密文件
     *
     * @param key
     * @param sourceFilePath
     * @param destFilePath
     * @return
     */
    public static File decryptFile(String key, String sourceFilePath, String destFilePath) {
        FileInputStream in = null;
        FileOutputStream out = null;
        File destFile = null;
        File sourceFile = null;
        try {
            sourceFile = new File(sourceFilePath);
            destFile = new File(destFilePath);
            if (sourceFile.exists() && sourceFile.isFile()) {
                if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }
                destFile.createNewFile();
                in = new FileInputStream(sourceFile);
                out = new FileOutputStream(destFile);
                Cipher cipher = initAESCipher(key, Cipher.DECRYPT_MODE);
                CipherOutputStream cipherOutputStream = new CipherOutputStream(out, cipher);
                byte[] buffer = new byte[1024];
                int r;
                while ((r = in.read(buffer)) >= 0) {
                    cipherOutputStream.write(buffer, 0, r);
                }
                cipherOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        return destFile;
    }
}

算法中用到了一個填充向量,即VIPARA,這個向量的取值是不固定的,但是加密秘鑰必須為16個字節,譬如“abcdefghabcdefgh”,經測試在java和android憑條是通用的,希望對大家日常開發的需求有所幫助。

 

 

來自:http://www.jianshu.com/p/2aa5e1a1df1a

 

 本文由用戶 RussBess 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!