C#DES加密,JavaDES解密,另转C#和Java实现Des完整代码

C#DES加密,JavaDES解密,另转C#和Java实现Des完整代码

转载 2014年06月17日 17:36:09
[java] view plain copy
 
  1. <span style="font-family: Arial, Helvetica, sans-serif;">今天,由于开发需要C#做DES加密,Java做DES解密,在实现时有这样一个问题:C#做DES有加密向量IV,Java常见方式是没有的。在解密时需要使用</span>  
[java] view plain copy
 
  1. Cipher cipher = Cipher.getInstance ( "DES/CBC/PKCS5Padding" );         
  2.        cipher.init(Cipher. DECRYPT_MODE , SecretKey mySecretKey , IvParameterSpec myIV);  

而不是
[java] view plain copy
 
  1. Cipher cipher = Cipher.getInstance ( "DES" );  
  2.        cipher.init(Cipher. DECRYPT_MODE , Key key );  

1、Java实现DES加解密(兼容C#DES加解密)

[java] view plain copy
 
  1. package decryption;  
  2.    
  3.   
  4.   
  5. import java.io.FileInputStream;    
  6. import java.io.FileOutputStream;   
  7. import java.io.InputStream;    
  8. import java.io.OutputStream;    
  9. import java.security.Key;   
  10.   
  11. import javax.crypto.Cipher;    
  12. import javax.crypto.CipherInputStream;    
  13. import javax.crypto.CipherOutputStream;   
  14.   
  15. import javax.crypto.SecretKey;  
  16. import javax.crypto.SecretKeyFactory;  
  17. import javax.crypto.spec.DESKeySpec;  
  18. import javax.crypto.spec.IvParameterSpec;  
  19.   
  20.   
  21.   
  22. public class Decryption {  
  23.        
  24.     Key key ;  
  25.     SecretKey mySecretKey;  
  26.     IvParameterSpec myIV;  
  27.    
  28.     public Decryption() {  
  29.    
  30.     }  
  31.    
  32.     public Decryption(String str) {  
  33.        setKey(str); // 生成密匙  
  34.     }  
  35.    
  36.     public Key getKey() {  
  37.        return key ;  
  38.     }  
  39.    
  40.     public void setKey(Key key) {  
  41.        this . key = key;  
  42.     }  
  43.    
  44.     /** 
  45.       * 根据参数生成 KEY 
  46.       */  
  47.     public void setKey(String strKey) {  
  48. //       try {  
  49. //           KeyGenerator _generator = KeyGenerator.getInstance ( "DES" );  
  50. //           _generator.init( new SecureRandom(strKey.getBytes()));  
  51. //           this . key = _generator.generateKey();  
  52. //           _generator = null ;  
  53. //       } catch (Exception e) {  
  54. //           throw new RuntimeException(  
  55. //                  "Error initializing SqlMap class. Cause: " + e);  
  56. //       }  
  57.         try {  
  58.         
  59.        DESKeySpec dks = new DESKeySpec(strKey.getBytes("UTF-8"));  
  60.          
  61.        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
  62.        SecretKey securekey = keyFactory.generateSecret(dks);  
  63.        this.mySecretKey=securekey;  
  64.          
  65.        byte[] Keys =strKey.getBytes();  
  66.        IvParameterSpec iv = new IvParameterSpec(Keys);  
  67.        this.myIV=iv;  
  68.          
  69.         } catch (Exception e) {  
  70.             throw new RuntimeException(e);  
  71.         }  
  72.     }  
  73.    
  74.   
  75.     
  76.     
  77.     /** 
  78.       * 文件 file 进行加密并保存目标文件 destFile 中 
  79.       * 
  80.       * @param file 
  81.       *             要加密的文件 如 c:/test/srcFile.txt 
  82.       * @param destFile 
  83.       *             加密后存放的文件名 如 c:/ 加密后文件 .txt 
  84.       */  
  85.     public void encryptFile(String file, String destFile) throws Exception {  
  86.        //Cipher cipher = Cipher.getInstance ( "DES" );  
  87.        // cipher.init(Cipher.ENCRYPT_MODE, getKey());  
  88.       // cipher.init(Cipher. ENCRYPT_MODE , this . key );  
  89.          
  90.         Cipher cipher = Cipher.getInstance ( "DES/CBC/PKCS5Padding" );          
  91.           
  92.         cipher.init(Cipher. ENCRYPT_MODE , mySecretKey ,myIV);  
  93.          
  94.        InputStream is = new FileInputStream(file);  
  95.        OutputStream out = new FileOutputStream(destFile);  
  96.        CipherInputStream cis = new CipherInputStream(is, cipher);  
  97.        byte [] buffer = new byte [1024];//原文件长度和缓冲区大小没有关系  
  98.        int r;  
  99.        while ((r = cis.read(buffer)) > 0) {  
  100.            out.write(buffer, 0, r);  
  101.        }  
  102.        cis.close();  
  103.        is.close();  
  104.        out.close();  
  105.     }  
  106.    
  107.     /** 
  108.       * 文件采用 DES 算法解密文件 
  109.       * 
  110.       * @param file 
  111.       *             已加密的文件 如 c:/ 加密后文件 .txt * 
  112.       * @param destFile 
  113.       *             解密后存放的文件名 如 c:/ test/ 解密后文件 .txt 
  114.       */  
  115.     public void decryptFile(String file, String dest) throws Exception {  
  116.       // Cipher cipher = Cipher.getInstance ( "DES" );  
  117.       // cipher.init(Cipher. DECRYPT_MODE , this . key );  
  118.           
  119.        Cipher cipher = Cipher.getInstance ( "DES/CBC/PKCS5Padding" );  
  120.          
  121.        cipher.init(Cipher. DECRYPT_MODE , mySecretKey ,myIV);  
  122.          
  123.        InputStream is = new FileInputStream(file);  
  124.        OutputStream out = new FileOutputStream(dest);  
  125.        CipherOutputStream cos = new CipherOutputStream(out, cipher);  
  126.        byte [] buffer = new byte [1024];//原文件长度和缓冲区大小没有关系  
  127.        int r;  
  128.        while ((r = is.read(buffer)) >= 0) {  
  129.            cos.write(buffer, 0, r);  
  130.        }  
  131.        cos.close();  
  132.        out.close();  
  133.        is.close();  
  134.     }  
  135.       
  136.    
  137.     public static void main(String[] args) throws Exception {  
  138.        Decryption des = new Decryption( "12345678" );         
  139.          
  140.        //des.encryptFile("C:/Users/user/Desktop/TS1402883420_F1_D16_6_T9_50_20.mp4","C:/Users/user/Desktop/456.mp4");  
  141.        //des.decryptFile("C:/Users/user/Desktop/456.mp4","C:/Users/user/Desktop/789.mp4");  
  142.        des.decryptFile("C:/Users/user/Desktop/CSharpEncrypt.mp4","C:/Users/user/Desktop/xyz.mp4");  
  143.     }  
  144. }   

2、C#DES加解密

[csharp] view plain copy
 
  1. using System.Security.Cryptography;  
  2. using System.IO;  
  3. using System.Text;  
  4. using System;  
  5.   
  6.   
  7. namespace DES_CSharp  
  8. {  
  9.     public class Security  
  10.         {  
  11.       
  12.             //默认密钥向量  
  13.             private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };  
  14.       
  15.             /// <summary>  
  16.             /// DES加密字符串  
  17.             /// </summary>  
  18.             /// <param name="encryptString">待加密的字符串</param>  
  19.             /// <param name="encryptKey">加密密钥,要求为8位</param>  
  20.             /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>  
  21.             public static string EncryptDES(string encryptString, string encryptKey)  
  22.             {  
  23.                 try  
  24.                 {  
  25.                     byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));  
  26.                     byte[] rgbIV = Keys;  
  27.                     byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);  
  28.                     DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();  
  29.                     MemoryStream mStream = new MemoryStream();  
  30.                     CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);  
  31.                     cStream.Write(inputByteArray, 0, inputByteArray.Length);  
  32.                     cStream.FlushFinalBlock();  
  33.                     return Convert.ToBase64String(mStream.ToArray());  
  34.                 }  
  35.                 catch  
  36.                 {  
  37.                     return encryptString;  
  38.                 }  
  39.             }  
  40.       
  41.             /// <summary>  
  42.             /// DES解密字符串  
  43.             /// </summary>  
  44.             /// <param name="decryptString">待解密的字符串</param>  
  45.             /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>  
  46.             /// <returns>解密成功返回解密后的字符串,失败返源串</returns>  
  47.             public static string DecryptDES(string decryptString, string decryptKey)  
  48.             {  
  49.                 try  
  50.                 {  
  51.                     byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);  
  52.                     byte[] rgbIV = Keys;  
  53.                     byte[] inputByteArray = Convert.FromBase64String(decryptString);  
  54.                     DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();  
  55.                     MemoryStream mStream = new MemoryStream();  
  56.                     CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);  
  57.                     cStream.Write(inputByteArray, 0, inputByteArray.Length);  
  58.                     cStream.FlushFinalBlock();  
  59.                     return Encoding.UTF8.GetString(mStream.ToArray());  
  60.                 }  
  61.                 catch  
  62.                 {  
  63.                     return decryptString;  
  64.                 }  
  65.             }  
  66.      
  67.             #region 加密方法 图片加密  
  68.             /// <summary>  
  69.             /// 图片加密  
  70.             /// </summary>  
  71.             /// <param name="filePath">源文件</param>  
  72.             /// <param name="savePath">保存为文件名称</param>  
  73.             /// <param name="keyStr">密钥,要求为8位</param>  
  74.             public static void EncryptFile(string filePath, string savePath, string keyStr)  
  75.             {  
  76.                 //通过des加密  
  77.                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();  
  78.                 //通过流打开文件  
  79.                 FileStream fs = File.OpenRead(filePath);  
  80.                 //获取文件二进制字符  
  81.                 byte[] inputByteArray = new byte[fs.Length];  
  82.                 //读流文件  
  83.                 fs.Read(inputByteArray, 0, (int)fs.Length);  
  84.                 //关闭流  
  85.                 fs.Close();  
  86.                 //获得加密字符串二进制字符  
  87.                 byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);  
  88.       
  89.                 ////计算指定字节组指定区域哈希值  
  90.                 //SHA1 ha = new SHA1Managed();  
  91.                 //byte[] hb = ha.ComputeHash(keyByteArray);  
  92.                 ////加密密钥数组  
  93.                 //byte[] sKey = new byte[8];  
  94.                 ////加密变量  
  95.                 //byte[] sIV = new byte[8];  
  96.                 //for (int i = 0; i < 8; i++)  
  97.                 //    sKey[i] = hb[i];  
  98.                 //for (int i = 8; i < 16; i++)  
  99.                 //    sIV[i - 8] = hb[i];  
  100.                 byte[] sKey = keyByteArray;  
  101.                 byte[] sIV = keyByteArray;  
  102.                 //获取加密密钥      
  103.                 des.Key = sKey;  
  104.                 //设置加密初始化向量  
  105.                 des.IV = sIV;  
  106.                 MemoryStream ms = new MemoryStream();  
  107.                 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);  
  108.                 cs.Write(inputByteArray, 0, inputByteArray.Length);  
  109.                 cs.FlushFinalBlock();  
  110.                 fs = File.OpenWrite(savePath);  
  111.                 foreach (byte b in ms.ToArray())  
  112.                 {  
  113.                     fs.WriteByte(b);  
  114.       
  115.                 }  
  116.                 fs.Close();  
  117.                 cs.Close();  
  118.                 ms.Close();  
  119.             }  
  120.             #endregion  
  121.      
  122.             #region 解密方法 图片解密  
  123.             /// <summary>  
  124.             /// 图片解密  
  125.             /// </summary>  
  126.             /// <param name="filePath">源文件</param>  
  127.             /// <param name="savePath">保存文件</param>  
  128.             /// <param name="keyStr">密钥,要求为8位</param>  
  129.             public static void DecryptFile(string filePath, string savePath, string keyStr)  
  130.             {  
  131.                 //通过des解密  
  132.                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();  
  133.       
  134.                 //通过流读取文件  
  135.                 FileStream fs = File.OpenRead(filePath);  
  136.                 //获取文件二进制字符  
  137.                 byte[] inputByteArray = new byte[fs.Length];  
  138.                 //读取流文件  
  139.                 fs.Read(inputByteArray, 0, (int)fs.Length);  
  140.                 //关闭流  
  141.                 fs.Close();  
  142.                 //密钥数组  
  143.                 byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);  
  144.                 ////定义哈希变量  
  145.                 //SHA1 ha = new SHA1Managed();  
  146.                 ////计算指定字节组指定区域哈希值  
  147.                 //byte[] hb = ha.ComputeHash(keyByteArray);  
  148.                 ////加密密钥数组  
  149.                 //byte[] sKey = new byte[8];  
  150.                 ////加密变量  
  151.                 //byte[] sIV = new byte[8];  
  152.                 //for (int i = 0; i < 8; i++)  
  153.                 //    sKey[i] = hb[i];  
  154.                 //for (int i = 8; i < 16; i++)  
  155.                 //    sIV[i - 8] = hb[i];  
  156.   
  157.                 byte[] sKey = keyByteArray;  
  158.                 byte[] sIV = keyByteArray;  
  159.   
  160.                 //获取加密密钥  
  161.                 des.Key = sKey;  
  162.                 //加密变量  
  163.                 des.IV = sIV;  
  164.                 MemoryStream ms = new MemoryStream();  
  165.                 CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);  
  166.                 cs.Write(inputByteArray, 0, inputByteArray.Length);  
  167.                 cs.FlushFinalBlock();  
  168.                 fs = File.OpenWrite(savePath);  
  169.                 foreach (byte b in ms.ToArray())  
  170.                 {  
  171.                     fs.WriteByte(b);  
  172.                 }  
  173.                 fs.Close();  
  174.                 cs.Close();  
  175.                 ms.Close();  
  176.             }  
  177.             #endregion  
  178.      
  179.             #region 加密方法 图片加密  
  180.             /// <summary>  
  181.             /// 图片加密  
  182.             /// </summary>  
  183.             /// <param name="filePath">加密文件字节数组</param>  
  184.             /// <param name="savePath">保存为文件名称</param>  
  185.             /// <param name="keyStr">密钥,要求为8位</param>  
  186.             public static void EncryptFile(byte[] inputByteArray, string savePath, string keyStr)  
  187.             {  
  188.                 try  
  189.                 {  
  190.                     //通过des加密  
  191.                     DESCryptoServiceProvider des = new DESCryptoServiceProvider();  
  192.                     //获得加密字符串二进制字符  
  193.                     byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);  
  194.       
  195.                     //计算指定字节组指定区域哈希值  
  196.                     SHA1 ha = new SHA1Managed();  
  197.                     byte[] hb = ha.ComputeHash(keyByteArray);  
  198.                     //加密密钥数组  
  199.                     byte[] sKey = new byte[8];  
  200.                     //加密变量  
  201.                     byte[] sIV = new byte[8];  
  202.                     for (int i = 0; i < 8; i++)  
  203.                         sKey[i] = hb[i];  
  204.                     for (int i = 8; i < 16; i++)  
  205.                         sIV[i - 8] = hb[i];  
  206.                     //获取加密密钥  
  207.       
  208.                     des.Key = sKey;  
  209.                     //设置加密初始化向量  
  210.                     des.IV = sIV;  
  211.                     MemoryStream ms = new MemoryStream();  
  212.                     CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);  
  213.                     cs.Write(inputByteArray, 0, inputByteArray.Length);  
  214.                     cs.FlushFinalBlock();  
  215.                     FileStream fs = File.OpenWrite(savePath);  
  216.                     foreach (byte b in ms.ToArray())  
  217.                     {  
  218.                         fs.WriteByte(b);  
  219.       
  220.                     }  
  221.                     fs.Close();  
  222.                     cs.Close();  
  223.                     ms.Close();  
  224.                 }  
  225.                 catch (Exception ex)  
  226.                 {  
  227.                     System.Diagnostics.Trace.Write(ex.Message);  
  228.                 }  
  229.             }  
  230.             #endregion  
  231.      
  232.             #region 解密方法 图片解密  
  233.             /// <summary>  
  234.             /// 图片解密  
  235.             /// </summary>  
  236.             /// <param name="filePath">源文件</param>  
  237.             /// <param name="savePath">保存文件</param>  
  238.             /// <param name="keyStr">密钥,要求为8位</param>  
  239.             /// <returns>返回解密后的文件字节数组</returns>  
  240.             public static byte[] DecryptFile(string filePath, string keyStr)  
  241.             {  
  242.                 try  
  243.                 {  
  244.                     //通过des解密  
  245.                     DESCryptoServiceProvider des = new DESCryptoServiceProvider();  
  246.       
  247.                     //通过流读取文件  
  248.                     FileStream fs = File.OpenRead(filePath);  
  249.                     //获取文件二进制字符  
  250.                     byte[] inputByteArray = new byte[fs.Length];  
  251.                     //读取流文件  
  252.                     fs.Read(inputByteArray, 0, (int)fs.Length);  
  253.                     //关闭流  
  254.                     fs.Close();  
  255.                     //密钥数组  
  256.                     byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);  
  257.                     //定义哈希变量  
  258.                     SHA1 ha = new SHA1Managed();  
  259.                     //计算指定字节组指定区域哈希值  
  260.                     byte[] hb = ha.ComputeHash(keyByteArray);  
  261.                     //加密密钥数组  
  262.                     byte[] sKey = new byte[8];  
  263.                     //加密变量  
  264.                     byte[] sIV = new byte[8];  
  265.                     for (int i = 0; i < 8; i++)  
  266.                         sKey[i] = hb[i];  
  267.                     for (int i = 8; i < 16; i++)  
  268.                         sIV[i - 8] = hb[i];  
  269.                     //获取加密密钥  
  270.                     des.Key = sKey;  
  271.                     //加密变量  
  272.                     des.IV = sIV;  
  273.                     MemoryStream ms = new MemoryStream();  
  274.                     CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);  
  275.                     cs.Write(inputByteArray, 0, inputByteArray.Length);  
  276.                     cs.FlushFinalBlock();  
  277.                     byte[] b = ms.ToArray();  
  278.                     cs.Close();  
  279.                     ms.Close();  
  280.                     return b;  
  281.                 }  
  282.                 catch (Exception ex)  
  283.                 {  
  284.                     System.Diagnostics.Trace.Write(ex.Message);  
  285.                     return null;  
  286.                 }  
  287.             }  
  288.             #endregion  
  289.         }  
  290. }  

3、JavaDES加解密

[java] view plain copy
 
  1. package  test;  
  2.    
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.security.Key;  
  8. import java.security.SecureRandom;  
  9.    
  10. import javax.crypto.Cipher;  
  11. import javax.crypto.CipherInputStream;  
  12. import javax.crypto.CipherOutputStream;  
  13. import javax.crypto.KeyGenerator;  
  14.    
  15. import sun.misc.BASE64Decoder;  
  16. import sun.misc.BASE64Encoder;  
  17.    
  18. public class DESUtil {  
  19.    
  20.     Key key ;  
  21.    
  22.     public DESUtil() {  
  23.    
  24.     }  
  25.    
  26.     public DESUtil(String str) {  
  27.        setKey(str); // 生成密匙  
  28.     }  
  29.    
  30.     public Key getKey() {  
  31.        return key ;  
  32.     }  
  33.    
  34.     public void setKey(Key key) {  
  35.        this . key = key;  
  36.     }  
  37.    
  38.     /** 
  39.       * 根据参数生成 KEY 
  40.       */  
  41.     public void setKey(String strKey) {  
  42.        try {  
  43.            KeyGenerator _generator = KeyGenerator.getInstance ( "DES" );  
  44.            _generator.init( new SecureRandom(strKey.getBytes()));  
  45.            this . key = _generator.generateKey();  
  46.            _generator = null ;  
  47.        } catch (Exception e) {  
  48.            throw new RuntimeException(  
  49.                   "Error initializing SqlMap class. Cause: " + e);  
  50.        }  
  51.     }  
  52.    
  53.     /** 
  54.       * 加密 String 明文输入 ,String 密文输出 
  55.       */  
  56.     public String encryptStr(String strMing) {  
  57.        byte [] byteMi = null ;  
  58.        byte [] byteMing = null ;  
  59.        String strMi = "" ;  
  60.        BASE64Encoder base64en = new BASE64Encoder();  
  61.        try {  
  62.            byteMing = strMing.getBytes( "UTF8" );  
  63.            byteMi = this .encryptByte(byteMing);  
  64.            strMi = base64en.encode(byteMi);  
  65.        } catch (Exception e) {  
  66.            throw new RuntimeException(  
  67.                   "Error initializing SqlMap class. Cause: " + e);  
  68.        } finally {  
  69.            base64en = null ;  
  70.            byteMing = null ;  
  71.            byteMi = null ;  
  72.        }  
  73.        return strMi;  
  74.     }  
  75.    
  76.     /** 
  77.       * 解密 以 String 密文输入 ,String 明文输出 
  78.       * 
  79.       * @param strMi 
  80.       * @return 
  81.       */  
  82.     public String decryptStr(String strMi) {  
  83.        BASE64Decoder base64De = new BASE64Decoder();  
  84.        byte [] byteMing = null ;  
  85.        byte [] byteMi = null ;  
  86.        String strMing = "" ;  
  87.        try {  
  88.            byteMi = base64De.decodeBuffer(strMi);  
  89.            byteMing = this .decryptByte(byteMi);  
  90.            strMing = new String(byteMing, "UTF8" );  
  91.        } catch (Exception e) {  
  92.            throw new RuntimeException(  
  93.                   "Error initializing SqlMap class. Cause: " + e);  
  94.        } finally {  
  95.            base64De = null ;  
  96.            byteMing = null ;  
  97.            byteMi = null ;  
  98.        }  
  99.        return strMing;  
  100.     }  
  101.    
  102.     /** 
  103.       * 加密以 byte[] 明文输入 ,byte[] 密文输出 
  104.       * 
  105.       * @param byteS 
  106.       * @return 
  107.       */  
  108.     private byte [] encryptByte( byte [] byteS) {  
  109.        byte [] byteFina = null ;  
  110.        Cipher cipher;  
  111.        try {  
  112.            cipher = Cipher.getInstance ( "DES" );  
  113.            cipher.init(Cipher. ENCRYPT_MODE , key );  
  114.            byteFina = cipher.doFinal(byteS);  
  115.        } catch (Exception e) {  
  116.            throw new RuntimeException(  
  117.                   "Error initializing SqlMap class. Cause: " + e);  
  118.        } finally {  
  119.            cipher = null ;  
  120.        }  
  121.        return byteFina;  
  122.     }  
  123.    
  124.     /** 
  125.       * 解密以 byte[] 密文输入 , 以 byte[] 明文输出 
  126.       * 
  127.       * @param byteD 
  128.       * @return 
  129.       */  
  130.     private byte [] decryptByte( byte [] byteD) {  
  131.        Cipher cipher;  
  132.        byte [] byteFina = null ;  
  133.        try {  
  134.            cipher = Cipher.getInstance ( "DES" );  
  135.            cipher.init(Cipher. DECRYPT_MODE , key );  
  136.            byteFina = cipher.doFinal(byteD);  
  137.        } catch (Exception e) {  
  138.            throw new RuntimeException(  
  139.                   "Error initializing SqlMap class. Cause: " + e);  
  140.        } finally {  
  141.            cipher = null ;  
  142.        }  
  143.        return byteFina;  
  144.     }  
  145.    
  146.     /** 
  147.       * 文件 file 进行加密并保存目标文件 destFile 中 
  148.       * 
  149.       * @param file 
  150.       *             要加密的文件 如 c:/test/srcFile.txt 
  151.       * @param destFile 
  152.       *             加密后存放的文件名 如 c:/ 加密后文件 .txt 
  153.       */  
  154.     public void encryptFile(String file, String destFile) throws Exception {  
  155.        Cipher cipher = Cipher.getInstance ( "DES" );  
  156.        // cipher.init(Cipher.ENCRYPT_MODE, getKey());  
  157.        cipher.init(Cipher. ENCRYPT_MODE , this . key );  
  158.        InputStream is = new FileInputStream(file);  
  159.        OutputStream out = new FileOutputStream(destFile);  
  160.        CipherInputStream cis = new CipherInputStream(is, cipher);  
  161.        byte [] buffer = new byte [1024];  
  162.        int r;  
  163.        while ((r = cis.read(buffer)) > 0) {  
  164.            out.write(buffer, 0, r);  
  165.        }  
  166.        cis.close();  
  167.        is.close();  
  168.        out.close();  
  169.     }  
  170.    
  171.     /** 
  172.       * 文件采用 DES 算法解密文件 
  173.       * 
  174.       * @param file 
  175.       *             已加密的文件 如 c:/ 加密后文件 .txt * 
  176.       * @param destFile 
  177.       *             解密后存放的文件名 如 c:/ test/ 解密后文件 .txt 
  178.       */  
  179.     public void decryptFile(String file, String dest) throws Exception {  
  180.        Cipher cipher = Cipher.getInstance ( "DES" );  
  181.        cipher.init(Cipher. DECRYPT_MODE , this . key );  
  182.        InputStream is = new FileInputStream(file);  
  183.        OutputStream out = new FileOutputStream(dest);  
  184.        CipherOutputStream cos = new CipherOutputStream(out, cipher);  
  185.        byte [] buffer = new byte [1024];  
  186.        int r;  
  187.        while ((r = is.read(buffer)) >= 0) {  
  188.            cos.write(buffer, 0, r);  
  189.        }  
  190.        cos.close();  
  191.        out.close();  
  192.        is.close();  
  193.     }  
  194.    
  195.     public static void main(String[] args) throws Exception {  
  196.        DESUtil des = new DESUtil( "1234567" );  
  197.        // DES 加密文件  
  198.        // des.encryptFile("G:/test.doc", "G:/ 加密 test.doc");  
  199.        // DES 解密文件  
  200.        // des.decryptFile("G:/ 加密 test.doc", "G:/ 解密 test.doc");  
  201.        String str1 = " 要加密的字符串 test" ;  
  202.        // DES 加密字符串  
  203.        String str2 = des.encryptStr(str1);  
  204.        // DES 解密字符串  
  205.        String deStr = des.decryptStr(str2);  
  206.        System. out .println( " 加密前: " + str1);  
  207.        System. out .println( " 加密后: " + str2);  
  208.        System. out .println( " 解密后: " + deStr);  
  209.     }  
  210. }   


原文地址:https://www.cnblogs.com/amylis_chen/p/8679102.html