您的位置:首页 > 其它

个人笔记-简单文件加密解密

2015-01-10 15:40 225 查看
/**

           * 把文件srcFile加密后存储为destFile

           *

           * @param srcFile

           * @param destFile

           */

          private voidencrypt(String srcFile, String destFile, Key privateKey)

            throws Exception {

           SecureRandom sr =new SecureRandom();

           Cipher cipher =Cipher.getInstance("AES/CBC/PKCS5Padding");

           IvParameterSpec spec= new IvParameterSpec(privateKey.getEncoded());

          cipher.init(Cipher.ENCRYPT_MODE, privateKey, spec, sr);

           FileInputStream fis= new FileInputStream(srcFile);

           FileOutputStream fos= new FileOutputStream(destFile);

           byte[] b = newbyte[2048];

           while (fis.read(b)!= -1) {

           fos.write(cipher.doFinal(b));

           }

           fos.close();

           fis.close();

          }

          /**

           * 把文件srcFile解密后存储为destFile

           *

           * @param srcFile

           * @param destFile

           * @param privateKey

           * @throws Exception

           */

          private voiddecrypt(String srcFile, String destFile, Key privateKey)

            throws Exception {

           SecureRandom sr =new SecureRandom();

           Cipher ciphers =Cipher.getInstance("AES/CBC/PKCS5Padding");

           IvParameterSpec spec= new IvParameterSpec(privateKey.getEncoded());

          ciphers.init(Cipher.DECRYPT_MODE, privateKey, spec, sr);

           FileInputStream fis= new FileInputStream(srcFile);

           FileOutputStream fos= new FileOutputStream(destFile);

           byte[] b = newbyte[2064];

           while (fis.read(b)!= -1) {

           fos.write(ciphers.doFinal(b));

           }

           fos.close();

           fis.close();

          }

          

         private Key getKey(String keyPath) throws Exception {

                   String key = "1234567887654321";

                   byte[] b = key.getBytes();

                   SecretKeySpec dks = new SecretKeySpec(b,"AES");

                   return dks;

         }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: