1. 程式人生 > >C#DES加密,JavaDES解密,另轉C#和Java實現Des完整代碼

C#DES加密,JavaDES解密,另轉C#和Java實現Des完整代碼

sso output uri sta RM light ash for str

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. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.security.Key;
  7. import javax.crypto.Cipher;
  8. import javax.crypto.CipherInputStream;
  9. import javax.crypto.CipherOutputStream;
  10. import javax.crypto.SecretKey;
  11. import javax.crypto.SecretKeyFactory;
  12. import javax.crypto.spec.DESKeySpec;
  13. import javax.crypto.spec.IvParameterSpec;
  14. public class Decryption {
  15. Key key ;
  16. SecretKey mySecretKey;
  17. IvParameterSpec myIV;
  18. public Decryption() {
  19. }
  20. public Decryption(String str) {
  21. setKey(str); // 生成密匙
  22. }
  23. public Key getKey() {
  24. return key ;
  25. }
  26. public void setKey(Key key) {
  27. this . key = key;
  28. }
  29. /**
  30. * 根據參數生成 KEY
  31. */
  32. public void setKey(String strKey) {
  33. // try {
  34. // KeyGenerator _generator = KeyGenerator.getInstance ( "DES" );
  35. // _generator.init( new SecureRandom(strKey.getBytes()));
  36. // this . key = _generator.generateKey();
  37. // _generator = null ;
  38. // } catch (Exception e) {
  39. // throw new RuntimeException(
  40. // "Error initializing SqlMap class. Cause: " + e);
  41. // }
  42. try {
  43. DESKeySpec dks = new DESKeySpec(strKey.getBytes("UTF-8"));
  44. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  45. SecretKey securekey = keyFactory.generateSecret(dks);
  46. this.mySecretKey=securekey;
  47. byte[] Keys =strKey.getBytes();
  48. IvParameterSpec iv = new IvParameterSpec(Keys);
  49. this.myIV=iv;
  50. } catch (Exception e) {
  51. throw new RuntimeException(e);
  52. }
  53. }
  54. /**
  55. * 文件 file 進行加密並保存目標文件 destFile 中
  56. *
  57. * @param file
  58. * 要加密的文件 如 c:/test/srcFile.txt
  59. * @param destFile
  60. * 加密後存放的文件名 如 c:/ 加密後文件 .txt
  61. */
  62. public void encryptFile(String file, String destFile) throws Exception {
  63. //Cipher cipher = Cipher.getInstance ( "DES" );
  64. // cipher.init(Cipher.ENCRYPT_MODE, getKey());
  65. // cipher.init(Cipher. ENCRYPT_MODE , this . key );
  66. Cipher cipher = Cipher.getInstance ( "DES/CBC/PKCS5Padding" );
  67. cipher.init(Cipher. ENCRYPT_MODE , mySecretKey ,myIV);
  68. InputStream is = new FileInputStream(file);
  69. OutputStream out = new FileOutputStream(destFile);
  70. CipherInputStream cis = new CipherInputStream(is, cipher);
  71. byte [] buffer = new byte [1024];//原文件長度和緩沖區大小沒有關系
  72. int r;
  73. while ((r = cis.read(buffer)) > 0) {
  74. out.write(buffer, 0, r);
  75. }
  76. cis.close();
  77. is.close();
  78. out.close();
  79. }
  80. /**
  81. * 文件采用 DES 算法解密文件
  82. *
  83. * @param file
  84. * 已加密的文件 如 c:/ 加密後文件 .txt *
  85. * @param destFile
  86. * 解密後存放的文件名 如 c:/ test/ 解密後文件 .txt
  87. */
  88. public void decryptFile(String file, String dest) throws Exception {
  89. // Cipher cipher = Cipher.getInstance ( "DES" );
  90. // cipher.init(Cipher. DECRYPT_MODE , this . key );
  91. Cipher cipher = Cipher.getInstance ( "DES/CBC/PKCS5Padding" );
  92. cipher.init(Cipher. DECRYPT_MODE , mySecretKey ,myIV);
  93. InputStream is = new FileInputStream(file);
  94. OutputStream out = new FileOutputStream(dest);
  95. CipherOutputStream cos = new CipherOutputStream(out, cipher);
  96. byte [] buffer = new byte [1024];//原文件長度和緩沖區大小沒有關系
  97. int r;
  98. while ((r = is.read(buffer)) >= 0) {
  99. cos.write(buffer, 0, r);
  100. }
  101. cos.close();
  102. out.close();
  103. is.close();
  104. }
  105. public static void main(String[] args) throws Exception {
  106. Decryption des = new Decryption( "12345678" );
  107. //des.encryptFile("C:/Users/user/Desktop/TS1402883420_F1_D16_6_T9_50_20.mp4","C:/Users/user/Desktop/456.mp4");
  108. //des.decryptFile("C:/Users/user/Desktop/456.mp4","C:/Users/user/Desktop/789.mp4");
  109. des.decryptFile("C:/Users/user/Desktop/CSharpEncrypt.mp4","C:/Users/user/Desktop/xyz.mp4");
  110. }
  111. }

2、C#DES加解密

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

3、JavaDES加解密

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


C#DES加密,JavaDES解密,另轉C#和Java實現Des完整代碼