Advertisement
Guest User

Untitled

a guest
Oct 6th, 2015
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.93 KB | None | 0 0
  1. public static class Encryption {
  2.  
  3. public static string EncryptToString(string TextToEncrypt, byte[] Key, byte[] IV = null)
  4. {
  5. return ByteArrToString(EncryptStringToBytes(StrToByteArray(TextToEncrypt), Key, IV));
  6. }
  7.  
  8. public static string EncryptToString(byte[] BytesToEncrypt, byte[] Key, byte[] IV = null)
  9. {
  10. return ByteArrToString(EncryptStringToBytes(BytesToEncrypt, Key, IV));
  11. }
  12.  
  13. public static byte[] EncryptToBytes(string TextToEncrypt, byte[] Key, byte[] IV = null)
  14. {
  15. return EncryptStringToBytes(StrToByteArray(TextToEncrypt), Key, IV);
  16. }
  17.  
  18. public static byte[] EncryptToBytes(byte[] BytesToEncrypt, byte[] Key, byte[] IV = null)
  19. {
  20. return EncryptStringToBytes(BytesToEncrypt, Key, IV);
  21. }
  22.  
  23. public static string DecryptToString(string EncryptedText, byte[] Key,byte[] IV=null)
  24. {
  25. return ByteArrToString(DecryptStringFromBytes(StrToByteArray(EncryptedText), Key, IV));
  26. }
  27.  
  28. public static string DecryptToString(byte[] EncryptedBytes, byte[] Key,byte[] IV=null)
  29. {
  30. return ByteArrToString(DecryptStringFromBytes(EncryptedBytes, Key, IV));
  31. }
  32.  
  33. public static byte[] DecryptToBytes(string EncryptedText, byte[] Key,byte[] IV=null)
  34. {
  35. return DecryptStringFromBytes(StrToByteArray(EncryptedText), Key, IV);
  36. }
  37.  
  38. public static byte[] DecryptToBytes(byte[] EncryptedBytes, byte[] Key,byte[] IV=null)
  39. {
  40. return DecryptStringFromBytes(EncryptedBytes, Key, IV);
  41. }
  42.  
  43. private static byte[] EncryptStringToBytes(byte[] TextToEncrypt, byte[] Key, byte[] IV=null)
  44. {
  45. Debug.WriteLine("Password: " + ByteArrToString(Key));
  46. Debug.WriteLine("IV: " + ByteArrToString(IV));
  47.  
  48. byte[] encrypted;
  49. // Create an Rijndael object
  50. // with the specified key and IV.
  51. using (Rijndael rijAlg = Rijndael.Create())
  52. {
  53. rijAlg.Key = Key;
  54. rijAlg.IV = IV;
  55.  
  56. // Create a decrytor to perform the stream transform.
  57. ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
  58.  
  59. // Create the streams used for encryption.
  60. using (MemoryStream msEncrypt = new MemoryStream())
  61. {
  62. using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
  63. {
  64. using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
  65. {
  66. //Write all data to the stream.
  67. swEncrypt.Write(TextToEncrypt);
  68. }
  69. encrypted = msEncrypt.ToArray();
  70. }
  71. }
  72. }
  73.  
  74. // Return the encrypted bytes from the memory stream.
  75. return encrypted;
  76. }
  77.  
  78. private static byte[] DecryptStringFromBytes(byte[] EncryptedText, byte[] Key, byte[] IV)
  79. {
  80.  
  81. Debug.WriteLine("Password: " + ByteArrToString(Key));
  82. Debug.WriteLine("IV: " + ByteArrToString(IV));
  83.  
  84. byte[] fromEncrypt = new byte[EncryptedText.Length];
  85.  
  86. // Create an Rijndael object
  87. // with the specified key and IV.
  88. using (Rijndael rijAlg = Rijndael.Create())
  89. {
  90. rijAlg.Key = Key;
  91. rijAlg.IV = IV;
  92.  
  93. // Create a decrytor to perform the stream transform.
  94. ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
  95.  
  96. // Create the streams used for decryption.
  97. using (MemoryStream msDecrypt = new MemoryStream(EncryptedText))
  98. {
  99. using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
  100. {
  101. //read stream into byte array
  102. csDecrypt.Read(fromEncrypt,0,fromEncrypt.Length);
  103. }
  104. }
  105. }
  106.  
  107. return fromEncrypt;
  108. }
  109.  
  110. public static byte[] StrToByteArray(string str)
  111. {
  112. if (str.Length == 0)
  113. throw new Exception("Invalid string value in StrToByteArray");
  114.  
  115. byte[] bytes = new byte[str.Length * sizeof(char)];
  116. System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
  117. return bytes;
  118. }
  119.  
  120. public static string ByteArrToString(byte[] bytes)
  121. {
  122. char[] chars = new char[bytes.Length / sizeof(char)];
  123. System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
  124. return new string(chars);
  125. }
  126.  
  127. public static byte[] GetIV()
  128. {
  129. byte[] randomArray = new byte[16];
  130. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
  131. rng.GetBytes(randomArray);
  132. return randomArray;
  133. }
  134. }
  135.  
  136. byte[] iv = Encryption.GetIV();
  137. byte[] password=Encryption.StrToByteArray("password");
  138.  
  139. string encrypted=Encryption.EncryptToString("Hello", password, iv);
  140. Debug.WriteLine("Result: " + Encryption.DecryptToString(encrypted,password,iv));
  141.  
  142. using System;
  143. using System.Collections.Generic;
  144. using System.Linq;
  145. using System.Text;
  146. using System.Diagnostics;
  147. using System.Security.Cryptography;
  148. using System.IO;
  149.  
  150.  
  151. namespace Encryption_test_app
  152. {
  153. class Program
  154. {
  155. static void Main(string[] args)
  156. {
  157. var encoding = new UTF8Encoding(false, true);
  158. var cryptor = new RijndaelEncryptor();
  159.  
  160. var plainText = "Hello World!";
  161. Debug.Print("Plain Text: [{0}]", plainText);
  162.  
  163. byte[] cypherBytes = cryptor.Encrypt(encoding.GetBytes(plainText));
  164. string decryptedText = encoding.GetString(cryptor.Decrypt(cypherBytes));
  165.  
  166. Debug.Print("Decrypted Text: [{0}]", decryptedText);
  167. Debug.Print("PlainText == Decrypted Text: [{0}]", plainText == decryptedText);
  168. }
  169. }
  170.  
  171.  
  172.  
  173. /// <summary>
  174. /// Simple class to encrypt/decrypt a byte array using the <see cref="RijndaelManaged"/> cryptographic algorithm.
  175. /// </summary>
  176. public class RijndaelEncryptor : IDisposable
  177. {
  178.  
  179. private RijndaelManaged _crypt = new RijndaelManaged();
  180.  
  181. #region Constructors
  182.  
  183. /// <summary>
  184. /// Initializes a new instance of the <see cref="RijndaelEncryptor"/> class using a default key and initial vector (IV).
  185. /// </summary>
  186. public RijndaelEncryptor() : this("0nce @pon a time...", "There lived a princess who 1iked frogs...") { }
  187.  
  188. /// <summary>
  189. /// Initializes a new instance of the <see cref="RijndaelEncryptor"/> class using the plain text key and initial vector
  190. /// which are used to construct encrypted key and IV values using the maximum allowed key and iv sizes for
  191. /// the <see cref="RijndaelEncryptor"/> cryptographic algorithm.
  192. /// </summary>
  193. /// <param name="keyPassword"></param>
  194. /// <param name="ivPassword"></param>
  195. public RijndaelEncryptor(string keyPassword, string ivPassword)
  196. {
  197. if (string.IsNullOrEmpty(keyPassword)) throw new ArgumentOutOfRangeException("keyPassword", "Cannot be null or empty");
  198. if (string.IsNullOrEmpty(ivPassword)) throw new ArgumentOutOfRangeException("ivPassword", "Cannot be null or empty");
  199.  
  200. KeyPassword = keyPassword;
  201. IVPassword = ivPassword;
  202.  
  203. _crypt.KeySize = _crypt.LegalKeySizes[0].MaxSize;
  204.  
  205. EncryptKey = _stringToBytes(KeyPassword, _crypt.KeySize >> 3);
  206. EncryptIV = _stringToBytes(IVPassword, _crypt.BlockSize >> 3);
  207.  
  208. }
  209.  
  210. /// <summary>
  211. /// Initializes a new instance of the <see cref="RijndaelEncryptor"/> class using the user supplied key and initial vector arrays.
  212. /// NOTE: these arrays will be validated for use with the <see cref="RijndaelManaged"/> cypher.
  213. /// </summary>
  214. /// <param name="encryptedKey"></param>
  215. /// <param name="encryptedIV"></param>
  216. public RijndaelEncryptor(byte[] encryptedKey, byte[] encryptedIV)
  217. {
  218. if (encryptedKey == null) throw new ArgumentNullException("encryptedKey");
  219. if (encryptedIV == null) throw new ArgumentNullException("encryptedIV");
  220.  
  221. //Verify encrypted key length is valid for this cryptor algo.
  222. int keylen = encryptedKey.Length << 3;
  223. if (!_crypt.ValidKeySize(keylen))
  224. {
  225. string errmsg = "Encryption key length(" + keylen.ToString() + ") is not for this algorithm:" + _crypt.GetType().Name;
  226. throw new ApplicationException(errmsg);
  227. }
  228.  
  229. //Verify encrypted iv length is valid for this cryptor algo.
  230. int len = encryptedIV.Length << 3;
  231. if (len != _crypt.BlockSize)
  232. {
  233. string errmsg = "Encryption key length(" + len.ToString() + ") is not for this algorithm:" + _crypt.GetType().Name;
  234. throw new ApplicationException(errmsg);
  235. }
  236.  
  237. EncryptKey = encryptedKey;
  238. EncryptIV = encryptedIV;
  239. }
  240.  
  241. #endregion
  242.  
  243. /// <summary>
  244. /// Plain text encryption key. Is used to generate a encrypted key <see cref="EncryptKey"/>
  245. /// </summary>
  246. public string KeyPassword { get; private set; }
  247.  
  248. /// <summary>
  249. /// Plain text encryption initial vector. Is used to generate a encrypted IV <see cref="EncryptIV"/>
  250. /// </summary>
  251. public string IVPassword { get; private set; }
  252.  
  253. /// <summary>
  254. /// Encrypted encryption key. (Size must match one of the allowed sizes for this encryption method).
  255. /// </summary>
  256. public byte[] EncryptKey { get; private set; }
  257.  
  258. /// <summary>
  259. /// Encrypted encryption IV. (Size must match one of the allowed sizes for this encryption method).
  260. /// </summary>
  261. public byte[] EncryptIV { get; private set; }
  262.  
  263.  
  264. /// <summary>
  265. /// Encrypts the given byte array using the defined <see cref="EncryptKey"/> and <see cref="EncryptIV"/> values.
  266. /// </summary>
  267. /// <param name="plaintext"></param>
  268. /// <returns></returns>
  269. public byte[] Encrypt(byte[] plaintext)
  270. {
  271. return(_encrypt(plaintext, EncryptKey, EncryptIV));
  272. }
  273.  
  274. /// <summary>
  275. /// Decrypts the given byte array using the defined <see cref="EncryptKey"/> and <see cref="EncryptIV"/> values.
  276. /// </summary>
  277. /// <param name="cypherBytes"></param>
  278. /// <returns></returns>
  279. public byte[] Decrypt(byte[] cypherBytes)
  280. {
  281. return (_decrypt(cypherBytes, EncryptKey, EncryptIV));
  282. }
  283.  
  284.  
  285. #region Private Encryption methods
  286.  
  287.  
  288. /// <summary>
  289. /// Used to encrypt the plain-text key and iv values to not so easy to ready byte arrays of the given size.
  290. /// </summary>
  291. /// <param name="password"></param>
  292. /// <param name="KeyByteSize"></param>
  293. /// <returns></returns>
  294. private byte[] _stringToBytes(string password, int KeyByteSize)
  295. {
  296. byte[] salt = new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0xfe, 0x00, 0xa7, 0xd3, 0x02, 0x02, 0x97, 0xc4, 0xa5, 0x32 };
  297. PasswordDeriveBytes b = new PasswordDeriveBytes(password, salt);
  298. return (b.GetBytes(KeyByteSize));
  299. }
  300.  
  301. /// <summary>
  302. /// Encrypts the <paramref name="plainBytes"/> array using the given key and initial vector.
  303. /// </summary>
  304. /// <remarks>
  305. /// This routine embeds the length of the plain data at the beginning of the encrypted record. This would be
  306. /// frowed apon by crypto experts. However, if you dont do this you may get extraneous data (extra null bytes)
  307. /// at the end of the decrypted byte array. This embedded length is used to trim the final decrypted array to size.
  308. /// </remarks>
  309. /// <param name="plainBytes"></param>
  310. /// <param name="key"></param>
  311. /// <param name="iv"></param>
  312. /// <returns></returns>
  313. private byte[] _encrypt(byte[] plainBytes, byte[] key, byte[] iv)
  314. {
  315. try
  316. {
  317. // Create a MemoryStream.
  318. using (MemoryStream mStream = new MemoryStream())
  319. {
  320. // Create a CryptoStream using the MemoryStream
  321. // and the passed key and initialization vector (IV).
  322. using (CryptoStream cStream = new CryptoStream(mStream, _crypt.CreateEncryptor(key, iv), CryptoStreamMode.Write))
  323. {
  324.  
  325. // Write the byte array to the crypto stream and flush it.
  326. byte[] recordLen = BitConverter.GetBytes(plainBytes.Length);
  327. cStream.Write(recordLen, 0, recordLen.Length);
  328. cStream.Write(plainBytes, 0, plainBytes.Length);
  329.  
  330. if (!cStream.HasFlushedFinalBlock)
  331. {
  332. cStream.FlushFinalBlock();
  333. }
  334.  
  335. // Get an array of bytes from the
  336. // MemoryStream that holds the
  337. // encrypted data.
  338. return(mStream.ToArray());
  339.  
  340. }
  341. }
  342. }
  343. catch (CryptographicException ex)
  344. {
  345. throw new ApplicationException("**ERROR** occurred during Encryption", ex);
  346. }
  347.  
  348. }
  349.  
  350. /// <summary>
  351. /// Decrypts the <paramref name="cryptBytes"/> array using the given key and initial vector.
  352. /// </summary>
  353. /// <param name="plainBytes"></param>
  354. /// <param name="key"></param>
  355. /// <param name="iv"></param>
  356. /// <returns></returns>
  357. private byte[] _decrypt(byte[] cryptBytes, byte[] key, byte[] iv)
  358. {
  359. try
  360. {
  361. // Create a new MemoryStream using the passed
  362. // array of encrypted data.
  363. using (MemoryStream msDecrypt = new MemoryStream(cryptBytes))
  364. {
  365. // Create a CryptoStream using the MemoryStream
  366. // and the passed key and initialization vector (IV).
  367. using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, _crypt.CreateDecryptor(key, iv), CryptoStreamMode.Read))
  368. {
  369. byte[] recordLen = BitConverter.GetBytes((int)0);
  370. csDecrypt.Read(recordLen, 0, recordLen.Length);
  371. int length = BitConverter.ToInt32(recordLen, 0);
  372.  
  373. // Create buffer to hold the decrypted data.
  374. byte[] fromEncrypt = new byte[cryptBytes.Length - recordLen.Length];
  375.  
  376. // Read the decrypted data out of the crypto stream
  377. // and place it into the temporary buffer.
  378. csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
  379.  
  380. byte[] plainBytes = new byte[length];
  381. Array.Copy(fromEncrypt, plainBytes, length);
  382.  
  383. return (plainBytes);
  384. }
  385. }
  386. }
  387. catch (CryptographicException ex)
  388. {
  389. throw new ApplicationException("**ERROR** occurred during Decryption", ex);
  390. }
  391. }
  392.  
  393. #endregion
  394.  
  395. #region IDisposable Members
  396.  
  397. private bool disposed = false; //indicates if this instance has been disposed.
  398.  
  399. private void Dispose(bool disposing)
  400. {
  401. if (!this.disposed)
  402. {
  403. //Dispose managed objects
  404. if (disposing)
  405. {
  406. if (_crypt != null)
  407. {
  408. try { _crypt.Clear(); }
  409. finally { _crypt = null; }
  410. }
  411. }
  412.  
  413. //Dispose Unmanaged objects
  414. }
  415. this.disposed = true;
  416. }
  417.  
  418. public void Dispose()
  419. {
  420. Dispose(true);
  421. GC.SuppressFinalize(this);
  422. }
  423.  
  424. ~RijndaelEncryptor() { Dispose(false); }
  425.  
  426. #endregion
  427.  
  428.  
  429. }
  430.  
  431. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement