欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

android使用AES加密和解密文件實(shí)例代碼

 更新時(shí)間:2017年05月20日 16:54:59   作者:Joker-L  
本篇文章主要介紹了android使用AES加密和解密文件實(shí)例代碼,非常具有實(shí)用價(jià)值,需要的朋友可以參考下

前言

最近公司需要對(duì)本公司的一些下載文件進(jìn)行加密解密需求,也就嘗試去實(shí)現(xiàn)下,其實(shí)需要借助第三方的jar包:bcprov-jdk15on-155.jar,下載這個(gè)可以到網(wǎng)上搜或者下載本人的demo即可,注意:需要加密和解密的key是一致的才可以解密,不然就會(huì)解密失敗。不多說,直接上代碼。

效果圖


代碼:

實(shí)現(xiàn)加密解密邏輯代碼

package com.vsoontech.p2p.sample; 
 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.security.InvalidKeyException; 
import java.security.Key; 
import java.security.NoSuchAlgorithmException; 
import java.security.SecureRandom; 
 
import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.KeyGenerator; 
import javax.crypto.NoSuchPaddingException; 
import javax.crypto.ShortBufferException; 
 
/** 
 * @author zhou 
 * @since 2016/9/26 
 */ 
 
public enum AES { 
  INSTANCE; 
  private Key key; 
 
  /** 
   * 生成AES對(duì)稱秘鑰 
   */ 
  public String generateKey() throws NoSuchAlgorithmException { 
    KeyGenerator keygen = KeyGenerator.getInstance("AES"); 
    SecureRandom random = new SecureRandom(); 
    keygen.init(random); 
    this.key = keygen.generateKey(); 
    return "Algorithm Format Encoded:" + key.getAlgorithm() + " - " + key.getFormat() + " - " + new String(key.getEncoded()); 
  } 
 
  /** 
   * 加密 
   */ 
  public void encrypt(InputStream in) throws InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException { 
    this.crypt(in, null, Cipher.ENCRYPT_MODE); 
  } 
 
  /** 
   * 解密 
   */ 
  public String decrypt(InputStream in) throws InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException { 
    return this.crypt(in, Cipher.DECRYPT_MODE); 
  } 
 
  /** 
   * 加密 
   */ 
  public void encrypt(InputStream in, OutputStream out) throws InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException { 
    this.crypt(in, out, Cipher.ENCRYPT_MODE); 
  } 
 
  /** 
   * 解密 
   */ 
  public void decrypt(InputStream in, OutputStream out) throws InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException { 
    this.crypt(in, out, Cipher.DECRYPT_MODE); 
  } 
 
  /** 
   * 實(shí)際的加密解密過程 
   */ 
  public void crypt(InputStream in, OutputStream out, int mode) throws IOException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { 
    Cipher cipher = Cipher.getInstance("AES"); 
    cipher.init(mode, this.key); 
 
    int blockSize = cipher.getBlockSize(); 
    int outputSize = cipher.getOutputSize(blockSize); 
    byte[] inBytes = new byte[blockSize]; 
    byte[] outBytes = new byte[outputSize]; 
 
    int inLength = 0; 
    boolean more = true; 
    while (more) { 
      inLength = in.read(inBytes); 
      if (inLength == blockSize) {  //只要輸入數(shù)據(jù)塊具有全長度(長度可被8整除),調(diào)用update方法 
        int outLength = cipher.update(inBytes, 0, blockSize, outBytes); 
        if (out != null) out.write(outBytes, 0, outLength); 
      } else { 
        more = false; 
      } 
    } 
    if (inLength > 0)  //不具有全長度,調(diào)用doFinal方法 
      outBytes = cipher.doFinal(inBytes, 0, inLength); 
    else 
      outBytes = cipher.doFinal(); 
    if (out != null) { 
      out.write(outBytes); 
      out.flush(); 
    } 
  } 
 
  /** 
   * 實(shí)際的加密解密過程 
   */ 
  public String crypt(InputStream in, int mode) throws IOException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { 
    Cipher cipher = Cipher.getInstance("AES"); 
    cipher.init(mode, this.key); 
 
    int blockSize = cipher.getBlockSize(); 
    int outputSize = cipher.getOutputSize(blockSize); 
    byte[] inBytes = new byte[blockSize]; 
    byte[] outBytes = new byte[outputSize]; 
 
    int inLength = 0; 
    boolean more = true; 
    StringBuilder sb = new StringBuilder(); 
    while (more) { 
      inLength = in.read(inBytes); 
      if (inLength == blockSize) {  //只要輸入數(shù)據(jù)塊具有全長度(長度可被8整除),調(diào)用update方法 
        int outLength = cipher.update(inBytes, 0, blockSize, outBytes); 
      } else { 
        more = false; 
      } 
    } 
    if (inLength > 0)  //不具有全長度,調(diào)用doFinal方法 
      outBytes = cipher.doFinal(inBytes, 0, inLength); 
    else 
      outBytes = cipher.doFinal(); 
    sb.append(new String(outBytes)); 
    return sb.toString(); 
  } 
 
 
  public void setKey(Key key) { 
    this.key = key; 
  } 
 
  public Key getKey() { 
    return key; 
  } 
} 

生成秘鑰代碼

package com.vsoontech.p2p.sample; 
 
import org.bouncycastle.jce.provider.BouncyCastleProvider; 
 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.security.Key; 
import java.security.NoSuchAlgorithmException; 
 
import javax.crypto.Cipher; 
import javax.crypto.KeyGenerator; 
import javax.crypto.SecretKey; 
import javax.crypto.spec.IvParameterSpec; 
import javax.crypto.spec.SecretKeySpec; 
 
/** 
 * @author zhou 
 * @since 2016/9/26 
 */ 
 
public class AESKeyModel { 
  public static final String KEY_ALGORITHM = "AES"; 
  private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; 
  private String srcFile = "", destionFile = ""; 
 
  /** 
   * 初始化密鑰 
   * 
   * @return byte[] 密鑰 
   * @throws Exception 
   */ 
  public byte[] initSecretKey() { 
    //返回生成指定算法的秘密密鑰的 KeyGenerator 對(duì)象 
    KeyGenerator kg = null; 
    try { 
      kg = KeyGenerator.getInstance(KEY_ALGORITHM); 
    } catch (NoSuchAlgorithmException e) { 
      e.printStackTrace(); 
      return new byte[0]; 
    } 
    //初始化此密鑰生成器,使其具有確定的密鑰大小 
    //AES 要求密鑰長度為 128 
    kg.init(128); 
    //生成一個(gè)密鑰 
    SecretKey secretKey = kg.generateKey(); 
    return secretKey.getEncoded(); 
  } 
 
  public void setDestionFile(String destionFile) { 
    this.destionFile = destionFile; 
  } 
 
  public void setSrcFile(String srcFile) { 
    this.srcFile = srcFile; 
  } 
 
  /** 
   * 轉(zhuǎn)換密鑰 
   * 
   * @param key 二進(jìn)制密鑰 
   * @return 密鑰 
   */ 
  private static Key toKey(byte[] key) { 
    //生成密鑰 
    return new SecretKeySpec(key, KEY_ALGORITHM); 
  } 
 
  /** 
   * 加密 
   * 
   * @param data 待加密數(shù)據(jù) 
   * @param key 密鑰 
   * @return byte[]  加密數(shù)據(jù) 
   * @throws Exception 
   */ 
  public static byte[] encrypt(byte[] data, Key key) throws Exception { 
    return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM); 
  } 
 
  /** 
   * 加密 
   * 
   * @param data 待加密數(shù)據(jù) 
   * @param key 二進(jìn)制密鑰 
   * @return byte[]  加密數(shù)據(jù) 
   * @throws Exception 
   */ 
  public static byte[] encrypt(byte[] data, byte[] key) throws Exception { 
    return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM); 
  } 
 
 
  /** 
   * 加密 
   * 
   * @param data      待加密數(shù)據(jù) 
   * @param key       二進(jìn)制密鑰 
   * @param cipherAlgorithm 加密算法/工作模式/填充方式 
   * @return byte[]  加密數(shù)據(jù) 
   * @throws Exception 
   */ 
  public static byte[] encrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception { 
    //還原密鑰 
    Key k = toKey(key); 
    return encrypt(data, k, cipherAlgorithm); 
  } 
 
  /** 
   * 加密 
   * 
   * @param data      待加密數(shù)據(jù) 
   * @param key       密鑰 
   * @param cipherAlgorithm 加密算法/工作模式/填充方式 
   * @return byte[]  加密數(shù)據(jù) 
   * @throws Exception 
   */ 
  public static byte[] encrypt(byte[] data, Key key, String cipherAlgorithm) throws Exception { 
    //實(shí)例化 
    Cipher cipher = Cipher.getInstance(cipherAlgorithm); 
    //使用密鑰初始化,設(shè)置為加密模式 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
    //執(zhí)行操作 
    return cipher.doFinal(data); 
  } 
 
  /** 
   * 解密 
   * 
   * @param data 待解密數(shù)據(jù) 
   * @param key 二進(jìn)制密鑰 
   * @return byte[]  解密數(shù)據(jù) 
   * @throws Exception 
   */ 
  public static byte[] decrypt(byte[] data, byte[] key) throws Exception { 
    return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM); 
  } 
 
  /** 
   * 解密 
   * 
   * @param data 待解密數(shù)據(jù) 
   * @param key 密鑰 
   * @return byte[]  解密數(shù)據(jù) 
   * @throws Exception 
   */ 
  public static byte[] decrypt(byte[] data, Key key) throws Exception { 
    return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM); 
  } 
 
  /** 
   * 解密 
   * 
   * @param data      待解密數(shù)據(jù) 
   * @param key       二進(jìn)制密鑰 
   * @param cipherAlgorithm 加密算法/工作模式/填充方式 
   * @return byte[]  解密數(shù)據(jù) 
   * @throws Exception 
   */ 
  public static byte[] decrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception { 
    //還原密鑰 
    Key k = toKey(key); 
    return decrypt(data, k, cipherAlgorithm); 
  } 
 
  /** 
   * 解密 
   * 
   * @param data      待解密數(shù)據(jù) 
   * @param key       密鑰 
   * @param cipherAlgorithm 加密算法/工作模式/填充方式 
   * @return byte[]  解密數(shù)據(jù) 
   * @throws Exception 
   */ 
  public static byte[] decrypt(byte[] data, Key key, String cipherAlgorithm) throws Exception { 
    //實(shí)例化 
    Cipher cipher = Cipher.getInstance(cipherAlgorithm); 
    //使用密鑰初始化,設(shè)置為解密模式 
    cipher.init(Cipher.DECRYPT_MODE, key); 
    //執(zhí)行操作 
    return cipher.doFinal(data); 
  } 
 
  public void encryptionFile(Key sessionKey) throws Exception { 
    int len = 0; 
    byte[] buffer = new byte[1024]; 
    byte[] cipherbuffer = null; 
 
    // 使用會(huì)話密鑰對(duì)文件加密。 
    Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM, new BouncyCastleProvider()); 
    IvParameterSpec iv = new IvParameterSpec("0000000000123456".getBytes()); 
    cipher.init(Cipher.ENCRYPT_MODE, sessionKey, iv); 
 
    FileInputStream fis = new FileInputStream(new File(srcFile)); 
    FileOutputStream fos = new FileOutputStream(new File(destionFile)); 
 
    // 讀取原文,加密并寫密文到輸出文件。 
    while ((len = fis.read(buffer)) != -1) { 
      cipherbuffer = cipher.update(buffer, 0, len); 
      fos.write(cipherbuffer); 
      fos.flush(); 
    } 
    cipherbuffer = cipher.doFinal(); 
    fos.write(cipherbuffer); 
    fos.flush(); 
 
    if (fis != null) 
      fis.close(); 
    if (fos != null) 
      fos.close(); 
  } 
 
  public void descryptionFile(Key sessionKey) throws Exception { 
    int len = 0; 
    byte[] buffer = new byte[5 * 1024]; 
    byte[] plainbuffer = null; 
 
    Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM, new BouncyCastleProvider()); 
    IvParameterSpec iv = new IvParameterSpec("0000000000123456".getBytes()); 
    cipher.init(Cipher.DECRYPT_MODE, sessionKey, iv); 
 
    FileInputStream fis = new FileInputStream(new File(srcFile)); 
    FileOutputStream fos = new FileOutputStream(new File(destionFile)); 
 
    while ((len = fis.read(buffer)) != -1) { 
      plainbuffer = cipher.update(buffer, 0, len); 
      fos.write(plainbuffer); 
      fos.flush(); 
    } 
 
    plainbuffer = cipher.doFinal(); 
    fos.write(plainbuffer); 
    fos.flush(); 
 
    if (fis != null) 
      fis.close(); 
    if (fos != null) 
      fos.close(); 
  } 
} 

加密邏輯示例代碼

/** 
   * 加密 
   * 
   * @param path 
   * @param destionFile 
   */ 
  private void aes(String path, String destionFile) { 
    try { 
      Log.d(TAG, "aes Key: " + AES.INSTANCE.generateKey()); 
      FileInputStream fis = new FileInputStream(new File(path)); 
      FileOutputStream fos = new FileOutputStream(new File(destionFile)); 
      AES.INSTANCE.encrypt(fis, fos); 
    } catch (Exception e) { 
      Log.d(TAG, "Exception: " + e.toString()); 
      e.printStackTrace(); 
    } 
 
  } 

解密邏輯示例代碼:

/** 
   * AES解密文件 
   * 
   * @param path 需要解密的文件目錄 
   */ 
  private void aesJieMi(String path) { 
    File f = new File(path); 
    if (!f.exists() || f.isDirectory()) 
      Toast.makeText(getApplicationContext(), "該文件不合法!", Toast.LENGTH_SHORT).show(); 
    else { 
      String prefix = f.getName().substring(0, f.getName().indexOf('.')); 
      String suffix = f.getName().substring(f.getName().indexOf('.')); 
      String outjiemiFile = Environment.getExternalStorageDirectory() + File.separator + prefix + "AES_jieMi" + suffix; 
 
      AESKeyModel model_aes = new AESKeyModel(); 
      model_aes.setSrcFile(path); 
      model_aes.setDestionFile(outjiemiFile); 
 
      try { 
//        model_aes.descryptionFile(key_AES); 
        model_aes.descryptionFile(key_aes); 
        // TODO: 加密后的文件 
        RandomAccessFile raf = new RandomAccessFile(path, "rw"); 
        Log.d(TAG, "解密后 file length: " + raf.length()); 
        Log.d(TAG, "解密后 file content: " + raf.readLine()); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
  } 

總結(jié):

注意秘鑰需要一致。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • android開發(fā)基礎(chǔ)教程—打電話發(fā)短信

    android開發(fā)基礎(chǔ)教程—打電話發(fā)短信

    打電話發(fā)短信的功能已經(jīng)離不開我們的生活了,記下來介紹打電話發(fā)短信的具體實(shí)現(xiàn)代碼,感興趣的朋友可以了解下
    2013-01-01
  • 詳解android 通過uri獲取bitmap圖片并壓縮

    詳解android 通過uri獲取bitmap圖片并壓縮

    這篇文章主要介紹了詳解android 通過uri獲取bitmap圖片并壓縮的相關(guān)資料,希望通過本文能幫助到大家,讓大家理解這部分內(nèi)容,需要的朋友可以參考下
    2017-10-10
  • wenserver獲取天氣預(yù)報(bào)數(shù)據(jù)實(shí)例分享

    wenserver獲取天氣預(yù)報(bào)數(shù)據(jù)實(shí)例分享

    wenserver獲取天氣預(yù)報(bào)數(shù)據(jù),實(shí)現(xiàn)android顯示天氣信息
    2013-12-12
  • Android實(shí)現(xiàn)掃雷小游戲

    Android實(shí)現(xiàn)掃雷小游戲

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)掃雷小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-11-11
  • cocos2d-2.0-x-2.0.3 交叉編譯到android報(bào)錯(cuò)解決

    cocos2d-2.0-x-2.0.3 交叉編譯到android報(bào)錯(cuò)解決

    我用的是cocos2d-2.0-x-2.0.3 之前弄了一天也沒成功 今天來了下載了最新的ndk8 更新了sdk 又重新是了一遍 居然成功了,不知道是工具的版本問題還是哪一步出錯(cuò)誤了,在這里詳細(xì)的整理一下,感興趣的朋友可以了解下
    2013-01-01
  • Android仿微信長按菜單效果

    Android仿微信長按菜單效果

    這篇文章主要為大家詳細(xì)介紹了Android仿微信長按菜單效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Android實(shí)現(xiàn)圖片雙指縮放

    Android實(shí)現(xiàn)圖片雙指縮放

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)圖片雙指縮放,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Flutter?Widget?之StatefulBuilder構(gòu)建方法詳解

    Flutter?Widget?之StatefulBuilder構(gòu)建方法詳解

    這篇文章主要為大家介紹了Flutter?Widget?之StatefulBuilder構(gòu)建方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • Android微信端的下拉刷新功能

    Android微信端的下拉刷新功能

    在微信公眾號(hào)內(nèi),在面對(duì)下拉刷新這個(gè)問題上,Android和iOS都自己的表現(xiàn)方式。下面通過本文給大家分享Android微信端的下拉刷新功能,需要的朋友參考下吧
    2017-06-06
  • Studio 編譯報(bào)錯(cuò):compileSdkVersion ''android-24'' requires JDK 1.8 or later to compile.的解決辦法

    Studio 編譯報(bào)錯(cuò):compileSdkVersion ''android-24'' requires JDK 1.

    今天小編就為大家分享一篇關(guān)于Studio編譯報(bào)錯(cuò):compileSdkVersion 'android-24' requires JDK 1.8 or later to compile.的解決辦法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-10-10

最新評(píng)論