1. 程式人生 > 其它 >安卓開發—圖片加密傳輸【檔案加密傳輸處理】

安卓開發—圖片加密傳輸【檔案加密傳輸處理】

技術標籤:技術總結開發新技術影象選擇(包括二維碼)圖片加密檔案IO加密安卓加密傳輸加密解密base64

廢話不說了,綜合考慮就是先對檔案進行加密,然後傳輸,服務端成功接收檔案後再對檔案進行解密 幹!

下面的程式碼,最後面就是,嗯~大家開心的工作吧,嘿嘿

/**
 * 資料加密
 * mazhanzhu
 */
public class AES128Util {
    //金鑰
    public static final String AESKEY = "**************";
    //偏移量
    public static final String IVVAL = "**************";
    //演算法名
    public static final String DATA_KEY = "AES";
    //加解密演算法/模式/填充方式
    //可以任意選擇,為了方便後面與iOS端的加密解密,採用與其相同的模式與填充方式
    //ECB模式只用金鑰即可對資料進行加密解密,CBC模式需要新增一個引數iv
    public static final String DATA_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    //生成金鑰
    private static byte[] generateKey(String aesKey) throws Exception {
        //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        
   /*   KeyGenerator kgen =KeyGenerator.getInstance(KEY_ALGORITHM);
        kgen.init(128, new SecureRandom(aesKey.getBytes()));
		SecretKey secretKey = kgen.generateKey();
		byte[] encodeFormat = secretKey.getEncoded();
		SecretKeySpec keySpec = new SecretKeySpec(encodeFormat, "AES");
        return keySpec.getEncoded();*/
        return aesKey.getBytes();
    }

    //生成iv
    private static AlgorithmParameters generateIV(String ivVal) throws Exception {
        //iv 為一個 16 位元組的陣列,這裡採用和 iOS 端一樣的構造方法,資料全為0
        //byte[] iv = new byte[16];
        //Arrays.fill(iv, (byte) 0x00);
        //Arrays.fill(iv,ivVal.getBytes());
        byte[] iv = ivVal.getBytes();
        AlgorithmParameters params = AlgorithmParameters.getInstance(DATA_KEY);
        params.init(new IvParameterSpec(iv));
        return params;
    }

    //轉化成JAVA的金鑰格式
    private static Key convertToKey(byte[] keyBytes) throws Exception {
        SecretKey secretKey = new SecretKeySpec(keyBytes, DATA_KEY);
        return secretKey;
    }

    /**
     * 加密
     *
     * @param plainText
     * @return
     */
    public static String JiaMi(String plainText) {
        try {
            byte[] data = plainText.getBytes();
            AlgorithmParameters iv = generateIV(IVVAL);
            byte[] keyBytes = generateKey(AESKEY);
            //轉化為金鑰
            Key key = convertToKey(keyBytes);
            //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(DATA_CIPHER_ALGORITHM);
            //設定為加密模式
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);
            byte[] encryptData = cipher.doFinal(data);
            return bytesToHexString(encryptData);
        } catch (Exception e) {
            Log_Ma.e("加密報錯", e.toString());
            return "";
        }
    }

    /**
     * 解密
     */
    public static String JieMi(String encryptedStr) {
        try {
            byte[] encryptedData = hexStringToByte(encryptedStr);
            byte[] keyBytes = generateKey(AESKEY);
            Key key = convertToKey(keyBytes);
            Cipher cipher = Cipher.getInstance(DATA_CIPHER_ALGORITHM);
            AlgorithmParameters iv = generateIV(IVVAL);
            //設定為解密模式
            cipher.init(Cipher.DECRYPT_MODE, key, iv);
            byte[] decryptData = cipher.doFinal(encryptedData);
            return new String(decryptData);
        } catch (Exception e) {
            Log_Ma.e("解密報錯", e.toString());
            return "";
        }
    }

    /**
     * 十六進位制字串轉換成陣列
     *
     * @param hex
     * @return
     */
    private static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static byte toByte(char c) {
        byte b = (byte) "0123456789abcdef".indexOf(c);
        return b;
    }


    /**
     * 把位元組陣列轉換成16進位制字串
     *
     * @param bArray
     * @return
     */
    private static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toLowerCase());
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        //明文
        String plainTextString = "111";
        System.out.println("明文 : " + plainTextString);
        String aesKey = "S9u978Q31NGPGc5H";
        String ivVal = "X83yESM9iShLxflS";
        try {
            //進行加密
            String encryptedData = JiaMi(plainTextString);
            //輸出加密後的資料
            System.out.println("加密後的資料 : ");
            System.out.println(encryptedData);
            System.out.println();
            String data = AES128Util.JieMi(encryptedData);
            System.out.println("解密得到的資料 : " + data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //fixme -----------檔案加密------------------------------------------------------------

    private static final byte[] IMG_KEY = {56, 57, 58, 59, 60, 61, 62, 63};//祕鑰長度必須是8 位或以上
    private static final String IMG_ALGORITHM = "DES";//祕鑰長度必須是8 位或以上
    private static final String IMG_CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";

    /**
     * 檔案進行加密並儲存加密後的檔案到指定目錄
     *
     * @param fromFilePath 要加密的檔案 如c:/test/待加密檔案.txt
     * @param toFilePath   加密後存放的檔案 如c:/加密後文件.txt
     */
    public static void encrypt(String fromFilePath, String toFilePath) {
        Log_Ma.e("encrypting...");
        File fromFile = new File(fromFilePath);
        if (!fromFile.exists()) {
            Log_Ma.e("to be encrypt file no exist!");
            return;
        }
        File toFile = getFile(toFilePath);

        SecretKey secretKey = new SecretKeySpec(IMG_KEY, IMG_ALGORITHM);
        InputStream is = null;
        OutputStream out = null;
        CipherInputStream cis = null;
        try {
            Cipher cipher = Cipher.getInstance(IMG_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            is = new FileInputStream(fromFile);
            out = new FileOutputStream(toFile);
            cis = new CipherInputStream(is, cipher);
            byte[] buffer = new byte[1024];
            int r;
            while ((r = cis.read(buffer)) > 0) {
                out.write(buffer, 0, r);
            }
        } catch (Exception e) {
            Log_Ma.e(e.toString());
        } finally {
            try {
                if (cis != null) {
                    cis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log_Ma.e("encrypt completed");
    }

    private static File getFile(String filePath) {
        File fromFile = new File(filePath);
        if (!fromFile.getParentFile().exists()) {
            fromFile.getParentFile().mkdirs();
        }
        return fromFile;
    }

    /**
     * 檔案進行解密並儲存解密後的檔案到指定目錄
     *
     * @param fromFilePath 已加密的檔案 如c:/加密後文件.txt
     * @param toFilePath   解密後存放的檔案 如c:/ test/解密後文件.txt
     */
    public static void decrypt(String fromFilePath, String toFilePath) {
        Log_Ma.e("decrypting...");

        File fromFile = new File(fromFilePath);
        if (!fromFile.exists()) {
            Log_Ma.e("to be decrypt file no exist!");
            return;
        }
        File toFile = getFile(toFilePath);

        SecretKey secretKey = new SecretKeySpec(IMG_KEY, IMG_ALGORITHM);

        InputStream is = null;
        OutputStream out = null;
        CipherOutputStream cos = null;
        try {
            Cipher cipher = Cipher.getInstance(IMG_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            is = new FileInputStream(fromFile);
            out = new FileOutputStream(toFile);
            cos = new CipherOutputStream(out, cipher);
            byte[] buffer = new byte[1024];
            int r;
            while ((r = is.read(buffer)) >= 0) {
                cos.write(buffer, 0, r);
            }
        } catch (Exception e) {
            Log_Ma.e(e.toString());
        } finally {
            try {
                if (cos != null) {
                    cos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log_Ma.e("decrypt completed");
    }
}