Ei kuvausta

EncDec.cs 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. namespace WpfApplication19
  5. {
  6. //
  7. // This sample code is provided "AS IS" with no warranties,
  8. // and confers no rights.
  9. //
  10. // ATTENTION: This sample is designed to be more of a
  11. // tutorial rather than something you can copy and paste in
  12. // the production code!
  13. //
  14. //
  15. // Sample encrypt/decrypt functions
  16. // Parameter checks and error handling
  17. // are ommited for better readability
  18. //
  19. public class EncDec
  20. {
  21. // Encrypt a byte array into a byte array using a key and an IV
  22. public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
  23. {
  24. // Create a MemoryStream to accept the encrypted bytes
  25. MemoryStream ms = new MemoryStream();
  26. // Create a symmetric algorithm.
  27. // We are going to use Rijndael because it is strong and
  28. // available on all platforms.
  29. // You can use other algorithms, to do so substitute the
  30. // next line with something like
  31. // TripleDES alg = TripleDES.Create();
  32. Rijndael alg = Rijndael.Create();
  33. // Now set the key and the IV.
  34. // We need the IV (Initialization Vector) because
  35. // the algorithm is operating in its default
  36. // mode called CBC (Cipher Block Chaining).
  37. // The IV is XORed with the first block (8 byte)
  38. // of the data before it is encrypted, and then each
  39. // encrypted block is XORed with the
  40. // following block of plaintext.
  41. // This is done to make encryption more secure.
  42. // There is also a mode called ECB which does not need an IV,
  43. // but it is much less secure.
  44. alg.Key = Key;
  45. alg.IV = IV;
  46. // Create a CryptoStream through which we are going to be
  47. // pumping our data.
  48. // CryptoStreamMode.Write means that we are going to be
  49. // writing data to the stream and the output will be written
  50. // in the MemoryStream we have provided.
  51. CryptoStream cs = new CryptoStream(ms,
  52. alg.CreateEncryptor(), CryptoStreamMode.Write);
  53. // Write the data and make it do the encryption
  54. cs.Write(clearData, 0, clearData.Length);
  55. // Close the crypto stream (or do FlushFinalBlock).
  56. // This will tell it that we have done our encryption and
  57. // there is no more data coming in,
  58. // and it is now a good time to apply the padding and
  59. // finalize the encryption process.
  60. cs.Close();
  61. // Now get the encrypted data from the MemoryStream.
  62. // Some people make a mistake of using GetBuffer() here,
  63. // which is not the right way.
  64. byte[] encryptedData = ms.ToArray();
  65. return encryptedData;
  66. }
  67. // Encrypt a string into a string using a password
  68. // Uses Encrypt(byte[], byte[], byte[])
  69. public static string Encrypt(string clearText, string Password)
  70. {
  71. // First we need to turn the input string into a byte array.
  72. byte[] clearBytes =
  73. System.Text.Encoding.Unicode.GetBytes(clearText);
  74. // Then, we need to turn the password into Key and IV
  75. // We are using salt to make it harder to guess our key
  76. // using a dictionary attack -
  77. // trying to guess a password by enumerating all possible words.
  78. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  79. new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  80. 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  81. // Now get the key/IV and do the encryption using the
  82. // function that accepts byte arrays.
  83. // Using PasswordDeriveBytes object we are first getting
  84. // 32 bytes for the Key
  85. // (the default Rijndael key length is 256bit = 32bytes)
  86. // and then 16 bytes for the IV.
  87. // IV should always be the block size, which is by default
  88. // 16 bytes (128 bit) for Rijndael.
  89. // If you are using DES/TripleDES/RC2 the block size is
  90. // 8 bytes and so should be the IV size.
  91. // You can also read KeySize/BlockSize properties off
  92. // the algorithm to find out the sizes.
  93. byte[] encryptedData = Encrypt(clearBytes,
  94. pdb.GetBytes(32), pdb.GetBytes(16));
  95. // Now we need to turn the resulting byte array into a string.
  96. // A common mistake would be to use an Encoding class for that.
  97. //It does not work because not all byte values can be
  98. // represented by characters.
  99. // We are going to be using Base64 encoding that is designed
  100. //exactly for what we are trying to do.
  101. return Convert.ToBase64String(encryptedData);
  102. }
  103. // Encrypt bytes into bytes using a password
  104. // Uses Encrypt(byte[], byte[], byte[])
  105. public static byte[] Encrypt(byte[] clearData, string Password)
  106. {
  107. // We need to turn the password into Key and IV.
  108. // We are using salt to make it harder to guess our key
  109. // using a dictionary attack -
  110. // trying to guess a password by enumerating all possible words.
  111. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  112. new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  113. 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  114. // Now get the key/IV and do the encryption using the function
  115. // that accepts byte arrays.
  116. // Using PasswordDeriveBytes object we are first getting
  117. // 32 bytes for the Key
  118. // (the default Rijndael key length is 256bit = 32bytes)
  119. // and then 16 bytes for the IV.
  120. // IV should always be the block size, which is by default
  121. // 16 bytes (128 bit) for Rijndael.
  122. // If you are using DES/TripleDES/RC2 the block size is 8
  123. // bytes and so should be the IV size.
  124. // You can also read KeySize/BlockSize properties off the
  125. // algorithm to find out the sizes.
  126. return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16));
  127. }
  128. // Encrypt a file into another file using a password
  129. public static void Encrypt(string fileIn,
  130. string fileOut, string Password)
  131. {
  132. // First we are going to open the file streams
  133. FileStream fsIn = new FileStream(fileIn,
  134. FileMode.Open, FileAccess.Read);
  135. FileStream fsOut = new FileStream(fileOut,
  136. FileMode.OpenOrCreate, FileAccess.Write);
  137. // Then we are going to derive a Key and an IV from the
  138. // Password and create an algorithm
  139. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  140. new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  141. 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  142. Rijndael alg = Rijndael.Create();
  143. alg.Key = pdb.GetBytes(32);
  144. alg.IV = pdb.GetBytes(16);
  145. // Now create a crypto stream through which we are going
  146. // to be pumping data.
  147. // Our fileOut is going to be receiving the encrypted bytes.
  148. CryptoStream cs = new CryptoStream(fsOut,
  149. alg.CreateEncryptor(), CryptoStreamMode.Write);
  150. // Now will will initialize a buffer and will be processing
  151. // the input file in chunks.
  152. // This is done to avoid reading the whole file (which can
  153. // be huge) into memory.
  154. int bufferLen = 4096;
  155. byte[] buffer = new byte[bufferLen];
  156. int bytesRead;
  157. do {
  158. // read a chunk of data from the input file
  159. bytesRead = fsIn.Read(buffer, 0, bufferLen);
  160. // encrypt it
  161. cs.Write(buffer, 0, bytesRead);
  162. } while(bytesRead != 0);
  163. // close everything
  164. // this will also close the unrelying fsOut stream
  165. cs.Close();
  166. fsIn.Close();
  167. }
  168. // Decrypt a byte array into a byte array using a key and an IV
  169. public static byte[] Decrypt(byte[] cipherData,
  170. byte[] Key, byte[] IV)
  171. {
  172. // Create a MemoryStream that is going to accept the
  173. // decrypted bytes
  174. MemoryStream ms = new MemoryStream();
  175. // Create a symmetric algorithm.
  176. // We are going to use Rijndael because it is strong and
  177. // available on all platforms.
  178. // You can use other algorithms, to do so substitute the next
  179. // line with something like
  180. // TripleDES alg = TripleDES.Create();
  181. Rijndael alg = Rijndael.Create();
  182. // Now set the key and the IV.
  183. // We need the IV (Initialization Vector) because the algorithm
  184. // is operating in its default
  185. // mode called CBC (Cipher Block Chaining). The IV is XORed with
  186. // the first block (8 byte)
  187. // of the data after it is decrypted, and then each decrypted
  188. // block is XORed with the previous
  189. // cipher block. This is done to make encryption more secure.
  190. // There is also a mode called ECB which does not need an IV,
  191. // but it is much less secure.
  192. alg.Key = Key;
  193. alg.IV = IV;
  194. // Create a CryptoStream through which we are going to be
  195. // pumping our data.
  196. // CryptoStreamMode.Write means that we are going to be
  197. // writing data to the stream
  198. // and the output will be written in the MemoryStream
  199. // we have provided.
  200. CryptoStream cs = new CryptoStream(ms,
  201. alg.CreateDecryptor(), CryptoStreamMode.Write);
  202. // Write the data and make it do the decryption
  203. cs.Write(cipherData, 0, cipherData.Length);
  204. // Close the crypto stream (or do FlushFinalBlock).
  205. // This will tell it that we have done our decryption
  206. // and there is no more data coming in,
  207. // and it is now a good time to remove the padding
  208. // and finalize the decryption process.
  209. cs.Close();
  210. // Now get the decrypted data from the MemoryStream.
  211. // Some people make a mistake of using GetBuffer() here,
  212. // which is not the right way.
  213. byte[] decryptedData = ms.ToArray();
  214. return decryptedData;
  215. }
  216. // Decrypt a string into a string using a password
  217. // Uses Decrypt(byte[], byte[], byte[])
  218. public static string Decrypt(string cipherText, string Password)
  219. {
  220. // First we need to turn the input string into a byte array.
  221. // We presume that Base64 encoding was used
  222. byte[] cipherBytes = Convert.FromBase64String(cipherText);
  223. // Then, we need to turn the password into Key and IV
  224. // We are using salt to make it harder to guess our key
  225. // using a dictionary attack -
  226. // trying to guess a password by enumerating all possible words.
  227. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  228. new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65,
  229. 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  230. // Now get the key/IV and do the decryption using
  231. // the function that accepts byte arrays.
  232. // Using PasswordDeriveBytes object we are first
  233. // getting 32 bytes for the Key
  234. // (the default Rijndael key length is 256bit = 32bytes)
  235. // and then 16 bytes for the IV.
  236. // IV should always be the block size, which is by
  237. // default 16 bytes (128 bit) for Rijndael.
  238. // If you are using DES/TripleDES/RC2 the block size is
  239. // 8 bytes and so should be the IV size.
  240. // You can also read KeySize/BlockSize properties off
  241. // the algorithm to find out the sizes.
  242. byte[] decryptedData = Decrypt(cipherBytes,
  243. pdb.GetBytes(32), pdb.GetBytes(16));
  244. // Now we need to turn the resulting byte array into a string.
  245. // A common mistake would be to use an Encoding class for that.
  246. // It does not work
  247. // because not all byte values can be represented by characters.
  248. // We are going to be using Base64 encoding that is
  249. // designed exactly for what we are trying to do.
  250. return System.Text.Encoding.Unicode.GetString(decryptedData);
  251. }
  252. // Decrypt bytes into bytes using a password
  253. // Uses Decrypt(byte[], byte[], byte[])
  254. public static byte[] Decrypt(byte[] cipherData, string Password)
  255. {
  256. // We need to turn the password into Key and IV.
  257. // We are using salt to make it harder to guess our key
  258. // using a dictionary attack -
  259. // trying to guess a password by enumerating all possible words.
  260. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  261. new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  262. 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  263. // Now get the key/IV and do the Decryption using the
  264. //function that accepts byte arrays.
  265. // Using PasswordDeriveBytes object we are first getting
  266. // 32 bytes for the Key
  267. // (the default Rijndael key length is 256bit = 32bytes)
  268. // and then 16 bytes for the IV.
  269. // IV should always be the block size, which is by default
  270. // 16 bytes (128 bit) for Rijndael.
  271. // If you are using DES/TripleDES/RC2 the block size is
  272. // 8 bytes and so should be the IV size.
  273. // You can also read KeySize/BlockSize properties off the
  274. // algorithm to find out the sizes.
  275. return Decrypt(cipherData, pdb.GetBytes(32), pdb.GetBytes(16));
  276. }
  277. // Decrypt a file into another file using a password
  278. public static void Decrypt(string fileIn,
  279. string fileOut, string Password)
  280. {
  281. // First we are going to open the file streams
  282. FileStream fsIn = new FileStream(fileIn,
  283. FileMode.Open, FileAccess.Read);
  284. FileStream fsOut = new FileStream(fileOut,
  285. FileMode.OpenOrCreate, FileAccess.Write);
  286. // Then we are going to derive a Key and an IV from
  287. // the Password and create an algorithm
  288. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
  289. new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
  290. 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
  291. Rijndael alg = Rijndael.Create();
  292. alg.Key = pdb.GetBytes(32);
  293. alg.IV = pdb.GetBytes(16);
  294. // Now create a crypto stream through which we are going
  295. // to be pumping data.
  296. // Our fileOut is going to be receiving the Decrypted bytes.
  297. CryptoStream cs = new CryptoStream(fsOut,
  298. alg.CreateDecryptor(), CryptoStreamMode.Write);
  299. // Now will will initialize a buffer and will be
  300. // processing the input file in chunks.
  301. // This is done to avoid reading the whole file (which can be
  302. // huge) into memory.
  303. int bufferLen = 4096;
  304. byte[] buffer = new byte[bufferLen];
  305. int bytesRead;
  306. do {
  307. // read a chunk of data from the input file
  308. bytesRead = fsIn.Read(buffer, 0, bufferLen);
  309. // Decrypt it
  310. cs.Write(buffer, 0, bytesRead);
  311. } while(bytesRead != 0);
  312. // close everything
  313. cs.Close(); // this will also close the unrelying fsOut stream
  314. fsIn.Close();
  315. }
  316. }
  317. }