Java对文件压缩/加密/解密/解压缩的例子,DES/RS

系统 2631 0
<!-- Feedsky FEED发布代码开始 --> 如果您喜欢这些文章,欢迎点击此处订阅本Blog <!-- FEED自动发现标记开始 --> <link title="RSS 2.0" type="application/rss+xml" href="http://feed.feedsky.com/softwave" rel="alternate"> <!-- FEED自动发现标记结束 --> Blog 订阅

<!--Google 468*60横幅广告开始--><script type="text/javascript"><!-- google_ad_client = "pub-7343546549496470"; google_ad_width = 468; google_ad_height = 60; google_ad_format = "468x60_as"; google_ad_type = "image"; //2007-07-26: CSDN google_ad_channel = "6063905817"; google_color_border = "6699CC"; google_color_bg = "E6E6E6"; google_color_link = "FFFFFF"; google_color_text = "333333"; google_color_url = "AECCEB"; google_ui_features = "rc:6"; //--> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script><!--Google 468*60横幅广告结束-->

RSA压缩加密/解压缩解密
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. import java.security.Key;
  7. import java.security.KeyPair;
  8. import java.security.KeyPairGenerator;
  9. import java.security.PrivateKey;
  10. import java.security.PublicKey;
  11. import java.security.SecureRandom;
  12. import java.util.Properties;
  13. import java.util.UUID;
  14. import java.util.zip.ZipEntry;
  15. import java.util.zip.ZipInputStream;
  16. import java.util.zip.ZipOutputStream;

  17. import javax.crypto.Cipher;

  18. /**
  19. *对文件压缩加密/解密解压缩对象类
  20. *
  21. */
  22. public class ZipEncrypt{
  23. private static PrivateKeyprivateKey;
  24. private static PublicKeypublicKey;
  25. private static void directoryZip(ZipOutputStreamout,Filef,Stringbase)
  26. throws Exception{
  27. //如果传入的是目录
  28. if (f.isDirectory()){
  29. File[]fl=f.listFiles();
  30. //创建压缩的子目录
  31. out.putNextEntry( new ZipEntry(base+ "/" ));
  32. if (base.length()== 0 ){
  33. base= "" ;
  34. } else {
  35. base=base+ "/" ;
  36. }
  37. for ( int i= 0 ;i<fl.length;i++){
  38. directoryZip(out,fl[i],base+fl[i].getName());
  39. }
  40. } else {
  41. //把压缩文件加入rar中
  42. out.putNextEntry( new ZipEntry(base));
  43. FileInputStreamin= new FileInputStream(f);
  44. byte []bb= new byte [ 2048 ];
  45. int aa= 0 ;
  46. while ((aa=in.read(bb))!=- 1 ){
  47. out.write(bb, 0 ,aa);
  48. }
  49. in.close();
  50. }
  51. }

  52. /**
  53. *压缩文件
  54. *@paramzos
  55. *@paramfile
  56. *@throwsException
  57. */
  58. private static void fileZip(ZipOutputStreamzos,Filefile)
  59. throws Exception{
  60. if (file.isFile()){
  61. zos.putNextEntry( new ZipEntry(file.getName()));
  62. FileInputStreamfis= new FileInputStream(file);
  63. byte []bb= new byte [ 2048 ];
  64. int aa= 0 ;
  65. while ((aa=fis.read(bb))!=- 1 ){
  66. zos.write(bb, 0 ,aa);
  67. }
  68. fis.close();
  69. System.out.println(file.getName());
  70. } else {
  71. directoryZip(zos,file, "" );
  72. }
  73. }

  74. /**
  75. *解压缩文件
  76. *
  77. *@paramzis
  78. *@paramfile
  79. *@throwsException
  80. */
  81. private static void fileUnZip(ZipInputStreamzis,Filefile)
  82. throws Exception{
  83. ZipEntryzip=zis.getNextEntry();
  84. if (zip== null )
  85. return ;
  86. Stringname=zip.getName();
  87. Filef= new File(file.getAbsolutePath()+ "/" +name);
  88. if (zip.isDirectory()){
  89. f.mkdirs();
  90. fileUnZip(zis,file);
  91. } else {
  92. f.createNewFile();
  93. FileOutputStreamfos= new FileOutputStream(f);
  94. byte b[]= new byte [ 2048 ];
  95. int aa= 0 ;
  96. while ((aa=zis.read(b))!=- 1 ){
  97. fos.write(b, 0 ,aa);
  98. }
  99. fos.close();
  100. fileUnZip(zis,file);
  101. }
  102. }

  103. /**
  104. *对directory目录下的文件压缩,保存为指定的文件zipFile
  105. *
  106. *@paramdirectory
  107. *@paramzipFile
  108. */
  109. private static void zip(Stringdirectory,StringzipFile){
  110. try {
  111. ZipOutputStreamzos= new ZipOutputStream( new FileOutputStream(
  112. zipFile));
  113. fileZip(zos, new File(directory));
  114. zos.close();
  115. } catch (Exceptione){
  116. e.printStackTrace();
  117. }
  118. }

  119. /**
  120. *解压缩文件zipFile保存在directory目录下
  121. *
  122. *@paramdirectory
  123. *@paramzipFile
  124. */
  125. private static void unZip(Stringdirectory,StringzipFile){
  126. try {
  127. ZipInputStreamzis= new ZipInputStream(
  128. new FileInputStream(zipFile));
  129. Filef= new File(directory);
  130. f.mkdirs();
  131. fileUnZip(zis,f);
  132. zis.close();
  133. } catch (Exceptione){
  134. e.printStackTrace();
  135. }
  136. }

  137. /**
  138. *根据key的路径文件获得持久化成文件的key
  139. *<P>
  140. *例子:RsaEncrypt.getKey("c:/systemkey/private.key");
  141. *
  142. *@paramkeyPath
  143. *@return
  144. */
  145. public static KeygetKey(StringkeyPath) throws Exception{
  146. Keykey= null ;
  147. FileInputStreamfis= new FileInputStream(keyPath);
  148. ObjectInputStreamofs= new ObjectInputStream(fis);
  149. key=(Key)ofs.readObject();
  150. return key;
  151. }

  152. /**
  153. *把文件srcFile加密后存储为destFile
  154. *
  155. *@paramsrcFile
  156. *@paramdestFile
  157. */
  158. private static void encrypt(StringsrcFile,StringdestFile,KeyprivateKey)
  159. throws Exception{
  160. Ciphercipher=Cipher.getInstance( "RSA" );
  161. cipher.init(Cipher.ENCRYPT_MODE,privateKey);
  162. FileInputStreamfis= new FileInputStream(srcFile);
  163. FileOutputStreamfos= new FileOutputStream(destFile);
  164. byte []b= new byte [ 53 ];
  165. while (fis.read(b)!=- 1 ){
  166. fos.write(cipher.doFinal(b));
  167. }
  168. fos.close();
  169. fis.close();
  170. }

  171. /**
  172. *把文件srcFile解密后存储为destFile
  173. *
  174. *@paramsrcFile
  175. *@paramdestFile
  176. *@paramprivateKey
  177. *@throwsException
  178. */
  179. private static void decrypt(StringsrcFile,StringdestFile,KeyprivateKey)
  180. throws Exception{
  181. Ciphercipher=Cipher.getInstance( "RSA" );
  182. cipher.init(Cipher.DECRYPT_MODE,privateKey);
  183. FileInputStreamfis= new FileInputStream(srcFile);
  184. FileOutputStreamfos= new FileOutputStream(destFile);
  185. byte []b= new byte [ 64 ];
  186. while (fis.read(b)!=- 1 ){
  187. fos.write(cipher.doFinal(b));
  188. }
  189. fos.close();
  190. fis.close();
  191. }

  192. /**
  193. *对目录srcFile下的所有文件目录进行先压缩后操作,然后保存为destfile
  194. *
  195. *@paramsrcFile
  196. *要操作的目录如c:/test/test
  197. *@paramdestfile
  198. *压缩加密后存放的文件名如c:/加密压缩文件.zip
  199. *@paramkeyfile
  200. *公钥存放地点
  201. */
  202. public static void encryptZip(StringsrcFile,Stringdestfile,Stringkeyfile) throws Exception{
  203. SecureRandomsr= new SecureRandom();
  204. KeyPairGeneratorkg=KeyPairGenerator.getInstance( "RSA" );
  205. kg.initialize( 512 ,sr);
  206. //产生新密钥对
  207. KeyPairkp=kg.generateKeyPair();
  208. //获得私匙
  209. ZipEncrypt.privateKey=kp.getPrivate();
  210. //获得公钥
  211. ZipEncrypt.publicKey=kp.getPublic();
  212. Filef= new File(keyfile);
  213. f.createNewFile();
  214. FileOutputStreamfos= new FileOutputStream(f);
  215. ObjectOutputStreamdos= new ObjectOutputStream(fos);
  216. dos.writeObject(ZipEncrypt.publicKey);
  217. Filetemp= new File(UUID.randomUUID().toString()+ ".zip" );
  218. temp.deleteOnExit();
  219. //先压缩文件
  220. zip(srcFile,temp.getAbsolutePath());
  221. //对文件加密
  222. encrypt(temp.getAbsolutePath(),destfile,privateKey);
  223. temp.delete();
  224. }

  225. /**
  226. *对文件srcfile进行先解密后解压缩,然后解压缩到目录destfile下
  227. *
  228. *@paramsrcfile
  229. *要解密和解压缩的文件名如c:/目标.zip
  230. *@paramdestfile
  231. *解压缩后的目录如c:/abc
  232. *@parampublicKey
  233. *公钥
  234. */
  235. public static void decryptUnzip(Stringsrcfile,Stringdestfile,
  236. KeypublicKey) throws Exception{
  237. //先对文件解密
  238. Filetemp= new File(UUID.randomUUID().toString()+ ".zip" );
  239. temp.deleteOnExit();
  240. decrypt(srcfile,temp.getAbsolutePath(),publicKey);
  241. //解压缩
  242. unZip(destfile,temp.getAbsolutePath());
  243. temp.delete();
  244. }

  245. public static void main(Stringargs[]) throws Exception{
  246. Filef= new File( "." );
  247. Propertiesprop= new Properties();;
  248. FileInputStreamfis= new FileInputStream( "./conf.properties" );
  249. prop.load(fis);
  250. //要压缩的目录
  251. StringsrcPath=prop.getProperty( "SRC_PATH" );
  252. //压缩后的存放文件
  253. StringdestZip=prop.getProperty( "DEST_FILE" );
  254. //压缩加密后的publickey
  255. Stringkeyfile=prop.getProperty( "KEY_FILE" );
  256. ZipEncrypt.encryptZip(srcPath,destZip,keyfile);
  257. /*解密
  258. ZipEncrypt.decryptUnzip("e:/comXXX/comxxxx.zip","d:/comxxx",ZipEncrypt
  259. .getKey("e:/comXXX/public.key"));
  260. */
  261. }
  262. }
AES压缩加密/解压缩解密,网上一般用base64来对byte[]编码,其实不需要,指定AES/CBC/PKCS5Padding来指定加密解密时候位数不对的情况下,用pkcs5padding来附加位数,不过这个时候读解密的文件的时候,要多读16位的验证位就不会报异常
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.security.Key;
  6. import java.security.SecureRandom;
  7. import java.util.UUID;
  8. import java.util.zip.ZipEntry;
  9. import java.util.zip.ZipInputStream;
  10. import java.util.zip.ZipOutputStream;
  11. import javax.crypto.Cipher;
  12. import javax.crypto.KeyGenerator;
  13. import javax.crypto.SecretKey;
  14. import javax.crypto.spec.IvParameterSpec;
  15. import javax.crypto.spec.SecretKeySpec;
  16. /**
  17. *对文件加密/解密和压缩/解压缩对象类
  18. *@author赵成明
  19. */
  20. public class ZipEncrypt{
  21. private void directoryZip(ZipOutputStreamout,Filef,Stringbase)
  22. throws Exception{
  23. //如果传入的是目录
  24. if (f.isDirectory()){
  25. File[]fl=f.listFiles();
  26. //创建压缩的子目录
  27. out.putNextEntry( new ZipEntry(base+ "/" ));
  28. if (base.length()== 0 ){
  29. base= "" ;
  30. } else {
  31. base=base+ "/" ;
  32. }
  33. for ( int i= 0 ;i<fl.length;i++){
  34. directoryZip(out,fl[i],base+fl[i].getName());
  35. }
  36. } else {
  37. //把压缩文件加入rar中
  38. out.putNextEntry( new ZipEntry(base));
  39. FileInputStreamin= new FileInputStream(f);
  40. byte []bb= new byte [ 2048 ];
  41. int aa= 0 ;
  42. while ((aa=in.read(bb))!=- 1 ){
  43. out.write(bb, 0 ,aa);
  44. }
  45. in.close();
  46. }
  47. }
  48. /**
  49. *压缩文件
  50. *@paramzos
  51. *@paramfile
  52. *@throwsException
  53. */
  54. private void fileZip(ZipOutputStreamzos,Filefile)
  55. throws Exception{
  56. if (file.isFile()){
  57. zos.putNextEntry( new ZipEntry(file.getName()));
  58. FileInputStreamfis= new FileInputStream(file);
  59. byte []bb= new byte [ 2048 ];
  60. int aa= 0 ;
  61. while ((aa=fis.read(bb))!=- 1 ){
  62. zos.write(bb, 0 ,aa);
  63. }
  64. fis.close();
  65. System.out.println(file.getName());
  66. } else {
  67. directoryZip(zos,file, "" );
  68. }
  69. }
  70. /**
  71. *解压缩文件
  72. *
  73. *@paramzis
  74. *@paramfile
  75. *@throwsException
  76. */
  77. private void fileUnZip(ZipInputStreamzis,Filefile)
  78. throws Exception{
  79. ZipEntryzip=zis.getNextEntry();
  80. if (zip== null )
  81. return ;
  82. Stringname=zip.getName();
  83. Filef= new File(file.getAbsolutePath()+ "/" +name);
  84. if (zip.isDirectory()){
  85. f.mkdirs();
  86. fileUnZip(zis,file);
  87. } else {
  88. f.createNewFile();
  89. FileOutputStreamfos= new FileOutputStream(f);
  90. byte b[]= new byte [ 2048 ];
  91. int aa= 0 ;
  92. while ((aa=zis.read(b))!=- 1 ){
  93. fos.write(b, 0 ,aa);
  94. }
  95. fos.close();
  96. fileUnZip(zis,file);
  97. }
  98. }
  99. /**
  100. *对directory目录下的文件压缩,保存为指定的文件zipFile
  101. *
  102. *@paramdirectory
  103. *@paramzipFile
  104. */
  105. private void zip(Stringdirectory,StringzipFile){
  106. try {
  107. ZipOutputStreamzos= new ZipOutputStream( new FileOutputStream(
  108. zipFile));
  109. fileZip(zos, new File(directory));
  110. zos.close();
  111. } catch (Exceptione){
  112. e.printStackTrace();
  113. }
  114. }
  115. /**
  116. *解压缩文件zipFile保存在directory目录下
  117. *
  118. *@paramdirectory
  119. *@paramzipFile
  120. */
  121. private void unZip(Stringdirectory,StringzipFile){
  122. try {
  123. ZipInputStreamzis= new ZipInputStream( new FileInputStream(zipFile));
  124. Filef= new File(directory);
  125. f.mkdirs();
  126. fileUnZip(zis,f);
  127. zis.close();
  128. } catch (Exceptione){
  129. e.printStackTrace();
  130. }
  131. }
  132. /**
  133. *根据key的路径文件获得持久化成文件的key
  134. *<P>
  135. *例子:RsaEncrypt.getKey("c:/systemkey/private.key");
  136. *
  137. *@paramkeyPath
  138. *@return
  139. */
  140. private KeygetKey(StringkeyPath) throws Exception{
  141. FileInputStreamfis= new FileInputStream(keyPath);
  142. byte []b= new byte [ 16 ];
  143. fis.read(b);
  144. SecretKeySpecdks= new SecretKeySpec(b, "AES" );
  145. fis.close();
  146. return dks;
  147. }
  148. /**
  149. *把文件srcFile加密后存储为destFile
  150. *
  151. *@paramsrcFile
  152. *@paramdestFile
  153. */
  154. private void encrypt(StringsrcFile,StringdestFile,KeyprivateKey)
  155. throws Exception{
  156. SecureRandomsr= new SecureRandom();
  157. Ciphercipher=Cipher.getInstance( "AES/CBC/PKCS5Padding" );
  158. IvParameterSpecspec= new IvParameterSpec(privateKey.getEncoded());
  159. cipher.init(Cipher.ENCRYPT_MODE,privateKey,spec,sr);
  160. FileInputStreamfis= new FileInputStream(srcFile);
  161. FileOutputStreamfos= new FileOutputStream(destFile);
  162. byte []b= new byte [ 2048 ];
  163. while (fis.read(b)!=- 1 ){
  164. fos.write(cipher.doFinal(b));
  165. }
  166. fos.close();
  167. fis.close();
  168. }
  169. /**
  170. *把文件srcFile解密后存储为destFile
  171. *
  172. *@paramsrcFile
  173. *@paramdestFile
  174. *@paramprivateKey
  175. *@throwsException
  176. */
  177. private void decrypt(StringsrcFile,StringdestFile,KeyprivateKey)
  178. throws Exception{
  179. SecureRandomsr= new SecureRandom();
  180. Cipherciphers=Cipher.getInstance( "AES/CBC/PKCS5Padding" );
  181. IvParameterSpecspec= new IvParameterSpec(privateKey.getEncoded());
  182. ciphers.init(Cipher.DECRYPT_MODE,privateKey,spec,sr);
  183. FileInputStreamfis= new FileInputStream(srcFile);
  184. FileOutputStreamfos= new FileOutputStream(destFile);
  185. byte []b= new byte [ 2064 ];
  186. while (fis.read(b)!=- 1 ){
  187. fos.write(ciphers.doFinal(b));
  188. }
  189. fos.close();
  190. fis.close();
  191. }
  192. /**
  193. *对目录srcFile下的所有文件目录进行先压缩后操作,然后保存为destfile
  194. *
  195. *@paramsrcFile
  196. *要操作的目录如c:/test/test
  197. *@paramdestfile
  198. *压缩加密后存放的文件名如c:/加密压缩文件.zip
  199. *@paramkeyfile
  200. *公钥存放地点
  201. */
  202. public void encryptZip(StringsrcFile,Stringdestfile,Stringkeyfile) throws Exception{
  203. SecureRandomsr= new SecureRandom();
  204. KeyGeneratorkg=KeyGenerator.getInstance( "AES" );
  205. kg.init( 128 ,sr);
  206. SecretKeykey=kg.generateKey();
  207. Filef= new File(keyfile);
  208. if (!f.getParentFile().exists())
  209. f.getParentFile().mkdirs();
  210. f.createNewFile();
  211. FileOutputStreamfos= new FileOutputStream(f);
  212. fos.write(key.getEncoded());
  213. Filetemp= new File(UUID.randomUUID().toString()+ ".zip" );
  214. temp.deleteOnExit();
  215. //先压缩文件
  216. zip(srcFile,temp.getAbsolutePath());
  217. //对文件加密
  218. encrypt(temp.getAbsolutePath(),destfile,key);
  219. temp.delete();
  220. }
  221. /**
  222. *对文件srcfile进行先解密后解压缩,然后解压缩到目录destfile下
  223. *
  224. *@paramsrcfile
  225. *要解密和解压缩的文件名如c:/目标.zip
  226. *@paramdestfile
  227. *解压缩后的目录如c:/abc
  228. *@parampublicKey
  229. *公钥
  230. */
  231. public void decryptUnzip(Stringsrcfile,Stringdestfile,
  232. Stringkeyfile) throws Exception{
  233. //先对文件解密
  234. Filetemp= new File(UUID.randomUUID().toString()+ ".zip" );
  235. temp.deleteOnExit();
  236. decrypt(srcfile,temp.getAbsolutePath(), this .getKey(keyfile));
  237. //解压缩
  238. unZip(destfile,temp.getAbsolutePath());
  239. temp.delete();
  240. }
  241. public static void main(Stringargs[]) throws Exception{
  242. long a=System.currentTimeMillis();
  243. new ZipEncrypt().encryptZip( "e:/com" , "e:/comXXX/page.zip" , "e:/comXXX/public.key" );
  244. System.out.println(System.currentTimeMillis()-a);
  245. a=System.currentTimeMillis();
  246. new ZipEncrypt().decryptUnzip( "e:/comXXX/page.zip" , "e:/comxxx" , "e:/comXXX/public.key" );
  247. System.out.println(System.currentTimeMillis()-a);
  248. }
  249. }
加密:encryptZip
通过路径找到Key:getKey
解密:decryptUnzip

转自【http://topic.csdn.net/u/20081215/09/6ad763bd-a158-488a-8e5e-b34cec2a0424.html及http://www.blogjava.net/zhaochengming/archive/2007/09/03/142396.html】


<!--新Google 468*60横幅广告开始--><script type="text/javascript"><!-- google_ad_client = "pub-7343546549496470"; /* 468x60, 创建于 08-8-6 */ google_ad_slot = "7368701459"; google_ad_width = 468; google_ad_height = 60; //--> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script><!--新Google 468*60横幅广告结束-->

<!--新Google 468x15 横链接单元开始--><script type="text/javascript"><!-- google_ad_client = "pub-7343546549496470"; /* 468x15 横链接单元 */ google_ad_slot = "5785741422"; google_ad_width = 468; google_ad_height = 15; //--> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script><!--新Google 468x15 横链接单元结束-->

<!-- Google Reader shared发布代码开始 --><script type="text/javascript" src="http://www.google.com/reader/ui/publisher.js"></script><script type="text/javascript" src="http://www.google.com/reader/public/javascript/user/00697638153916680411/state/com.google/broadcast?n=5&amp;callback=GRC_p(%7Bc%3A%22green%22%2Ct%3A%22%5Cu8FD9%5Cu4E9B%5Cu6587%5Cu7AE0%5Cu4E5F%5Cu503C%5Cu5F97%5Cu4E00%5Cu770B%22%2Cs%3A%22false%22%7D)%3Bnew%20GRC"></script><!-- Google Reader shared发布代码结束 -->

Java对文件压缩/加密/解密/解压缩的例子,DES/RSA


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论