Android之AES對文件進行加密解密

加密解密工具類:

package com.xtm.test.util;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by TiamMing.Xiong on 2019/3/20.
 */
public class AESUtils {
    /**
     * 偏移量,必須是16位字符串,可修改,但必須保證加密解密都相同
     */
    private static final String IV_STRING = "1234567891234567";

    /**
     * 加密文件
     *
     * @param key
     * @param byteContent
     * @return
     */
    public static byte[] encryptData(String key, byte[] byteContent) {
        byte[] encryptedBytes = null;
        try {
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            // 用於產生密文的第一個block,以使最終生成的密文產生差異(明文相同的情況下),
            // 使密碼攻擊變得更爲困難,除此之外IvParameterSpec並無其它用途。
            // 爲了方便也可以動態跟隨key生成new IvParameterSpec(key.getBytes("utf-8"))
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            encryptedBytes = cipher.doFinal(byteContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedBytes;
    }

    /**
     * 解密文件
     *
     * @param key
     * @param encryptedBytes
     * @return
     */
    public static byte[] decryptData(String key, byte[] encryptedBytes) {
        byte[] result = null ;
        try {
            byte[] sEnCodeFormat = key.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(sEnCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            result = cipher.doFinal(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

 附上文件工具類:

package com.xtm.test.util;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 文件工具類
 */
public class FileUtil {
    private static final String TAG = FileUtil.class.getSimpleName();

    /**
     * 文件轉字節
     */
    public static byte[] file2Bytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                Log.w(TAG, filePath + " file is not exist!");
                return null;
            }
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 字節轉文件
     */
    public static File bytes2File(byte[] bfile, String filePath) {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        File file = null;
        try {
            file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if(!file.exists()){
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        Log.i(TAG, "file : " + file);
        return file;
    }

    /**
     * 大文件轉字節(推薦,性能較好)
     *
     * @param filePath 文件的絕對路徑
     * @return 轉換後的字節數組
     */
    public static byte[] bigFile2Bytes(String filePath) {
        byte[] result = null;
        FileChannel fc = null;
        try {
            fc = new RandomAccessFile(filePath, "rw").getChannel();
            MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0,
                    fc.size()).load();
            Log.i(TAG, "byteBuffer isLoaded :" + byteBuffer.isLoaded());
            result = new byte[(int) fc.size()];
            if (byteBuffer.remaining() > 0) {
                byteBuffer.get(result, 0, byteBuffer.remaining());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fc != null)
                    fc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.i(TAG, "bigFile2Bytes result: " + result);
        return result;
    }

    /**
     * Bitmap保存到文件
     *
     * @param bitmap   位圖
     * @param filePath 保存到的絕對路徑
     * @return 是否保存成功
     */
    public static boolean saveBitmap2File(Bitmap bitmap, String filePath) {
        boolean state = false;
        if (null == bitmap) {
            Log.e(TAG, " bitmap is null !");
            return state;
        }
        if (TextUtils.isEmpty(filePath)) {
            Log.e(TAG, " filePath is null !");
            return state;
        }
        File file = new File(filePath);
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if(!file.exists()){
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            Log.i(TAG, "file has save: " + filePath);
            state = true;
        } catch (Exception e) {
            e.printStackTrace();
            state = false;
        }
        return state;
    }

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章