Thursday, December 1, 2016

Sample Program to Encrypt and Decrypt string using RijndaelManaged in CSharp (C#)

Here is a class to Encrypt and Decrypt a given string using RijndaelManaged. You have to change the private variable value based on your strength requirement of the encryption.

Encryption:
  1. public static string Encrypt(string plainText)
  2. {
  3. byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
  4. byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
  5. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
  6. PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
  7. byte[] keyBytes = password.GetBytes(keySize / 8);
  8. RijndaelManaged symmetricKey = new RijndaelManaged();
  9. symmetricKey.Mode = CipherMode.CBC;
  10. ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
  11. MemoryStream memoryStream = new MemoryStream();
  12. CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
  13. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
  14. cryptoStream.FlushFinalBlock();
  15. byte[] cipherTextBytes = memoryStream.ToArray();
  16. memoryStream.Close();
  17. cryptoStream.Close();
  18. string cipherText = Convert.ToBase64String(cipherTextBytes);
  19. return cipherText;
  20. }
Decryption:
  1. public static string Decrypt(string cipherText)
  2. {
  3. byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
  4. byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
  5. byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
  6. PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
  7. byte[] keyBytes = password.GetBytes(keySize / 8);
  8. RijndaelManaged symmetricKey = new RijndaelManaged();
  9. symmetricKey.Mode = CipherMode.CBC;
  10. ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
  11. MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
  12. CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
  13. byte[] plainTextBytes = new byte[cipherTextBytes.Length];
  14. int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
  15. memoryStream.Close();
  16. cryptoStream.Close();
  17. string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
  18. return plainText;
  19. }
These private variables also needs to be initialized within the same class.
  1. private const string passPhrase = "Pas5pr@se";
  2. private const string saltValue = "s@1tValue";
  3. private const string hashAlgorithm = "MD5";
  4. private const int passwordIterations = 2;
  5. private const string initVector = "@1B2c3D4e5F6g7H8";
  6. private const int keySize = 256;

No comments:

Post a Comment