How to recode functions to use Strings instad of FileStreams - c#

I'm building a game which needs encrypted saves etc. So I'm making a few functions to help me encrypt them. However, the only function I currently have uses FileStreams for input and output, but I would like to use strings instead. The functions work fine on Files, but I'm having trouble swapping from FileStreams to MemoryStreams to strings.
NOTE: I HAVE REMOVED IRRELEVANT CODE. OurCodeWorld.GenerateRandomSalt() 100% works, tested with FileStream encryption
FULL CODE:
Program.cs:
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace Encryption_test
{
class Program
{
static public string encryptedExtension = ".aes";
static public string decryptedExtension = ".decrypted";
static void Main(string[] args)
{
string path = Environment.CurrentDirectory;
Log($"Current path: {path}");
string filePath = $"{path}/unencrypted.txt";
string message =
#"Hello world!
This is my message. 1234";
RunStackOverFlowString();
//Sleep forever...zzz
Thread.Sleep(10000);
Console.WriteLine();
float TicksToMs(long ticks)
{
return ticks / (float)Stopwatch.Frequency * 1000F;
}
void RunStackOverFlowString()
{
byte[] salt = OurCodeWorld.GenerateRandomSalt();
int iterations = 1024;
string password = "";
string enc = StackOverflow.EncryptString(message, password, salt, iterations);
Log($"Enc: {enc}");
string dec = StackOverflow.DecryptString(enc, password, salt, iterations);
Log($"Dec: {dec}");
}
private static void WriteFile(string path, string value)
{
FileStream _file = File.OpenWrite(path);
byte[] info = new UTF8Encoding(true).GetBytes(value);
_file.Write(info, 0, info.Length);
_file.Close();
}
private static string ReadFile(string filePath, long length = long.MaxValue)
{
FileStream _file = File.OpenRead(filePath);
if (length == long.MaxValue)
length = _file.Length;
byte[] b = new byte[length];
UTF8Encoding temp = new UTF8Encoding(true);
_file.Read(b, 0, b.Length);
_file.Close();
return temp.GetString(b);
}
private static void DeleteFile(string path)
{
File.Delete(path);
}
private static void CreateFile(string path)
{
if (File.Exists(path))
DeleteFile(path);
FileStream a = File.Open(path, FileMode.Create);
a.Close();
}
static void Log(string message)
{
Console.WriteLine(message);
}
}
}
StackOverFlow.cs:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class StackOverflow
{
// Rfc2898DeriveBytes constants:
/// <summary>Decrypt a file.</summary>
/// <remarks>NB: "Padding is invalid and cannot be removed." is the Universal CryptoServices error. Make sure the password, salt and iterations are correct before getting nervous.</remarks>
/// <param name="sourceFilename">The full path and name of the file to be decrypted.</param>
/// <param name="destinationFilename">The full path and name of the file to be output.</param>
/// <param name="password">The password for the decryption.</param>
/// <param name="salt">The salt to be applied to the password.</param>
/// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
public static void DecryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
using (FileStream destination = new FileStream(destinationFilename, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
try
{
using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
catch (CryptographicException exception)
{
if (exception.Message == "Padding is invalid and cannot be removed.")
throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
else
throw;
}
}
}
}
/// <summary>Encrypt a file.</summary>
/// <param name="sourceFilename">The full path and name of the file to be encrypted.</param>
/// <param name="destinationFilename">The full path and name of the file to be output.</param>
/// <param name="password">The password for the encryption.</param>
/// <param name="salt">The salt to be applied to the password.</param>
/// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
public static void EncryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);
using (FileStream destination = new FileStream(destinationFilename, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
}
}
//THIS IS MY CODE
public static string EncryptString(string inputString, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);
var source = StringToStream(inputString);
var output = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(output, transform, CryptoStreamMode.Write);
source.CopyTo(cryptoStream);
return StreamToString(output);
}
public static string DecryptString(string inputString, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
var source = StringToStream(inputString);
var output = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(output, transform, CryptoStreamMode.Write);
source.CopyTo(cryptoStream);
return StreamToString(output);
}
public static Stream StringToStream(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
public static string StreamToString(Stream s)
{
s.Position = 0;
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, (int)s.Length);
return Encoding.Default.GetString(buffer);
}
}
I have already tested the StreamToString and StringToStream methods, and they work fine. When I run DecryptString, there is no output, and the function returns garbled strings, often looking similar to this Dec: ?K???
?#?????n?l?r????T?

I tested the code. There are two issues:
You take encrypted bytes and convert them to a string using an encoding. This process will fail in general because you can't take arbitrary bytes and convert them to a string. The mapping between bytes and strings is not 1:1. Likely, you should not work with strings at all here. Rather, keep the data in byte format and write those bytes to a file. The method signature should be like byte[] Encrypt(byte[] input, ...). The encryption code has no business converting from and to strings.
EncryptString must flush the crypto stream using FlushFinalBlock. If this is not done data at the end will be missing.

Conversion between strings and binary data is done with and Encoding. The encoding determines how the characters will be converted into binary data. Common encosings are Unicode, UTF8 or ASCII. If you want predicatble results you need to use a specific encoding for both conversions.
In your StringToStream you do not specify your encoding at all, while you use Encoding.Default in StreamToString. Encoding.Default does not provide a predictable result, because it uses the current code page (if you are running on a Windows system). So you can not be sure that you are using the same encoding in both methods.
The solution is to provide the same encoding on both ends:
public static Stream StringToStream(string s)
{
byte[] buffer = Encoding.UTF8.GetBytes(s);
return new MemoryStream(buffer);
}
public static string StreamToString(Stream s)
{
s.Position = 0;
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, (int)s.Length);
return Encoding.UTF8.GetString(buffer);
}

Related

Padding is invalid and cannot be removed. c# decrypt AES Rijndael, AES Managed

I am trying to encrypt and decrypt the file. Using AES methods in a MVC web application. I am able to encrypt file and decrypt only once. If I try for second time it gives me "Padding is invalid and cannot be removed error."
I have tried almost every combination with different properties of AES properties.
I have tried using statement for disposing the objects.
I have tried using FlushFinalBlock() after CryptoStream write.
I have tried with using AES.Padding to Zero (gives me no error but the file doesnt decrypt ), AES.Padding to None gives me error('Length of the data to encrypt is invalid.'). AES.Padding to PKCS7 gives me error (padding is invalid.)
Please find my code below.
public class EncryptionDecryption
{
// Call this function to remove the key from memory after use for security
[DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(IntPtr Destination, int Length);
/// <summary>
/// Creates a random salt that will be used to encrypt your file. This method is required on FileEncrypt.
/// </summary>
/// <returns></returns>
public static byte[] GenerateRandomSalt()
{
byte[] data = new byte[32];
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
// Ten iterations.
for (int i = 0; i < 10; i++)
{
// Fill buffer.
rng.GetBytes(data);
}
}
return data;
}
/// <summary>
/// Encrypts a file from its path and a plain password.
/// </summary>
/// <param name="inputFile"></param>
/// <param name="password"></param>
public static void FileEncrypt(string inputFile, string password)
{
//generate random salt
byte[] salt = GenerateRandomSalt();
//create output file name
using (FileStream fsCrypt = new FileStream(inputFile + ".aes", FileMode.Create))
{
//convert password string to byte arrray
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
//Set Rijndael symmetric encryption algorithm
using (AesManaged AES = new AesManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
AES.Padding = PaddingMode.None;
//http://stackoverflow.com/questions/2659214/why-do-i-need-to-use-the-rfc2898derivebytes-class-in-net-instead-of-directly
//"What it does is repeatedly hash the user password along with the salt." High iteration counts.
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
//Cipher modes: http://security.stackexchange.com/questions/52665/which-is-the-best-cipher-mode-and-padding-mode-for-aes-encryption
AES.Mode = CipherMode.CBC;
// write salt to the begining of the output file, so in this case can be random every time
fsCrypt.Write(salt, 0, salt.Length);
using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
{
//create a buffer (1mb) so only this amount will allocate in the memory and not the whole file
byte[] buffer = new byte[1048576];
int read;
try
{
while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
{
// Application.DoEvents(); // -> for responsive GUI, using Task will be better!
cs.Write(buffer, 0, read);
}
// Close up
fsIn.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
if (!cs.HasFlushedFinalBlock)
cs.FlushFinalBlock();
cs.Close();
fsCrypt.Close();
}
}
}
}
}
}
/// <summary>
/// Decrypts an encrypted file with the FileEncrypt method through its path and the plain password.
/// </summary>
/// <param name="inputFile"></param>
/// <param name="outputFile"></param>
/// <param name="password"></param>
public static void FileDecrypt(string inputFile, string outputFile, string password)
{
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
byte[] salt = new byte[32];
using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
{
fsCrypt.Read(salt, 0, salt.Length);
using (AesManaged AES = new AesManaged ())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Padding = PaddingMode.PKCS7;
AES.Mode = CipherMode.CBC;
using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read))
{
using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
{
int read;
byte[] buffer = new byte[1048576];
try
{
while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
{
//Application.DoEvents();
fsOut.Write(buffer, 0, read);
//if (!cs.HasFlushedFinalBlock)
cs.FlushFinalBlock();
}
}
catch (CryptographicException ex_CryptographicException)
{
Console.WriteLine("CryptographicException error: " + ex_CryptographicException.Message);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
try
{
cs.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error by closing CryptoStream: " + ex.Message);
}
finally
{
fsOut.Close();
fsCrypt.Close();
}
}
}
}
}
}
}
calling methods
Encryption
string password = "ThePasswordToDecryptAndEncryptTheFile";
// For additional security Pin the password of your files
GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);
// Encrypt the file
EncryptionDecryption.FileEncrypt(inputFilePath, password);
// To increase the security of the encryption, delete the given password from the memory !
EncryptionDecryption.ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);
gch.Free();
Decryption
GCHandle gch2 = GCHandle.Alloc(password, GCHandleType.Pinned);
// Decrypt the file
EncryptionDecryption.FileDecrypt(encryptedFilePath, outputPath, password);
// To increase the security of the decryption, delete the used password from the memory !
EncryptionDecryption.ZeroMemory(gch2.AddrOfPinnedObject(), password.Length * 2);
gch2.Free();
I got it resolved by removing all the AES properties to default and just keeping few. Find the code below. Specially the padding fields.
public static void FileEncrypt(string inputFile, string outputFile, string password, byte[] salt)
{
try
{
using (RijndaelManaged AES = new RijndaelManaged())
{
byte[] passwordBytes = ASCIIEncoding.UTF8.GetBytes(password);
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
/* This is for demostrating purposes only.
* Ideally you will want the IV key to be different from your key and you should always generate a new one for each encryption in other to achieve maximum security*/
//byte[] IV = ASCIIEncoding.UTF8.GetBytes(skey);
using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
{
using (ICryptoTransform encryptor = AES.CreateEncryptor(AES.Key, AES.IV))
{
using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
{
int data;
while ((data = fsIn.ReadByte()) != -1)
{
cs.WriteByte((byte)data);
}
if (!cs.HasFlushedFinalBlock)
cs.FlushFinalBlock();
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public static void FileDecrypt(string inputFile, string outputFile, string password, byte[] salt)
{
try
{
using (RijndaelManaged AES = new RijndaelManaged())
{
//byte[] key = ASCIIEncoding.UTF8.GetBytes(password);
/* This is for demostrating purposes only.
* Ideally you will want the IV key to be different from your key and you should always generate a new one for each encryption in other to achieve maximum security*/
//byte[] IV = ASCIIEncoding.UTF8.GetBytes(password);
byte[] passwordBytes = ASCIIEncoding.UTF8.GetBytes(password);
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
{
using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
{
using (ICryptoTransform decryptor = AES.CreateDecryptor(AES.Key, AES.IV))
{
using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read))
{
int data;
while ((data = cs.ReadByte()) != -1)
{
fsOut.WriteByte((byte)data);
}
if (!cs.HasFlushedFinalBlock)
cs.FlushFinalBlock();
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
// failed to decrypt file
}
}
}

How to prepend AES ciphertext with IV

There seems to be a convention in which an IV can be stored in plaintext in the beginning of an AES encrypted file.
I can encrypt and decrypt a file successfully when providing both the key and the IV during both encryption and decryption. This uses the code below, with slight modification. If that code would help, please LMK and I'll add it.
However, if I try to write the IV to the beginning of the file in plain text, I cannot decrypt the content (not sure if it's really being encrypted right either).
Can someone point out what's wrong below? Not sure why the .NET framework doesn't have this a a built in option.
If anyone can point out ways in which I'm not following the aforementioned convention, please do point them out!
using System;
using System.Security.Cryptography;
public class AESBase : IDisposable
{
protected AesManaged AES;
protected ICryptoTransform CryptoTransform;
public AESBase(byte[] key, byte[] iv = null)
{
AES = new AesManaged
{
BlockSize = 128,
KeySize = 256,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
Key = key
};
if (iv != null) { AES.IV = iv; }
}
}
using System.IO;
using System.Security.Cryptography;
using System.Threading.Tasks;
internal class AESFiles : AESBase, IFileCrytpo
{
internal AESFiles(byte[] key, byte[] iv) : base(key, iv) { }
#region internal methods
public void Encrypt(string inputFileName, string outputFileName, bool overwriteFile)
{
CryptoTransform = AES.CreateEncryptor(AES.Key, AES.IV);
if (overwriteFile)
{
DeleteFile(outputFileName);
}
Transform(inputFileName, outputFileName, true);
}
public void Decrypt(string inputFileName, string outputFileName, bool overwriteFile)
{
CryptoTransform = AES.CreateDecryptor(AES.Key, AES.IV);
if (overwriteFile)
{
DeleteFile(outputFileName);
}
Transform(inputFileName, outputFileName, false);
}
#endregion public methods
#region private methods
private void Transform(string inputFileName, string outputFileName, bool encrypt)
{
var destination = new FileStream(outputFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
if (encrypt)
{
//put the IV unencrypted in the front of the string
destination.Write(AES.IV, 0, AES.BlockSize / 8);
}
var source = new FileStream(inputFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
if (!encrypt)
{
source.Read(AES.IV, 0, AES.BlockSize / 8);
//var temp = Encoding.UTF8.GetString(AES.IV);
}
Transform(source, destination, CryptoTransform);
}
private static void Transform(Stream inputStream, Stream outputStream, ICryptoTransform transform)
{
using (var cryptoStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write))
{
//inputStream.Position = AES.BlockSize/8 + 1; CryptographicException : Length of the data to decrypt is invalid.
//inputStream.Position = AES.BlockSize/8; CryptographicException : Padding is invalid and cannot be removed.
inputStream.CopyTo(cryptoStream);
cryptoStream.FlushFinalBlock();
}
}
private static void DeleteFile(string fileName)
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
#endregion private methods
}
[TestFixture]
class AESFilesTest
{
private const string Path = #"C:\Users\Joe\Desktop\";
private const string FileInput = "Input.csv";
private const string FileEncrypted = "Encrypted.csv";
private const string FileDecrypted = "Decrypted.csv";
private readonly string _fileContents = String.Format("Test3,Test4" + Environment.NewLine, "Test5,Test6");
private readonly byte[] _key;
private readonly byte[] _iv;
private readonly Engine _engine;
public AESFilesTest()
{
_engine = new Engine();
_key = Encoding.UTF8.GetBytes("CEC520FA51EA0A47E87295FA32442605"); //test key
_iv = Encoding.UTF8.GetBytes("FB423A0BCB2AF4A4"); //test iv
File.WriteAllText(Path + FileInput, _fileContents);
}
[Test]
public void decrypted_text_matches_original()
{
const string inputFileWithPath = Path + FileInput;
_engine.Encrypt(_key, _iv, inputFileWithPath, Path + FileEncrypted, true);
_engine.Decrypt(_key, Path + FileEncrypted, Path + FileDecrypted, true);
var decrypted = File.ReadAllText(Path + FileDecrypted);
Console.WriteLine(decrypted);
Assert.AreEqual(_fileContents, decrypted);
}
There were many errors... The correct code:
private void Transform(string inputFileName, string outputFileName, bool encrypt)
{
using (var source = new FileStream(inputFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var destination = new FileStream(outputFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
ICryptoTransform cryptoTransform;
if (encrypt)
{
//put the IV unencrypted in the front of the string
destination.Write(AES.IV, 0, AES.BlockSize / 8);
cryptoTransform = AES.CreateEncryptor(AES.Key, AES.IV);
}
else
{
byte[] bytes = new byte[AES.BlockSize / 8];
source.Read(bytes, 0, bytes.Length);
AES.IV = bytes;
cryptoTransform = AES.CreateDecryptor(AES.Key, AES.IV);
}
Transform(source, destination, cryptoTransform, encrypt);
}
}
private static void Transform(Stream inputStream, Stream outputStream, ICryptoTransform transform, bool encrypt)
{
using (var cryptoStream = new CryptoStream(encrypt ? outputStream : inputStream, transform, encrypt ? CryptoStreamMode.Write : CryptoStreamMode.Read))
{
//inputStream.Position = AES.BlockSize/8 + 1; CryptographicException : Length of the data to decrypt is invalid.
//inputStream.Position = AES.BlockSize/8; CryptographicException : Padding is invalid and cannot be removed.
if (encrypt)
{
inputStream.CopyTo(cryptoStream);
// Not needed. Done by the Dispose()
//cryptoStream.FlushFinalBlock();
}
else
{
cryptoStream.CopyTo(outputStream);
}
}
}
then remove the now useless
protected ICryptoTransform CryptoTransform;
In general, the handling of the encrypt and of the decrypt operation are totally different... In many places the parameters change.
Another problem was in the reading of the IV: you can't read directly into the IV property of AesManaged, you have to read to a temporary buffer (bytes) and then assign the buffer to IV.
Third problem: you have to create the CryptoTransform when you have the Key and the IV and you know if you want to encrypt or decrypt.
Ah... and note that you aren't writing the plain text IV, because the IV isn't text, it is binary. You are writing the IV in binary format (or in its native format... or whatever you want to call it). Unless with plaintext you meant the non-encrypted IV. Then yes, you are writing the plaintext version of it. But still you can't encode it with Encoding.UTF8, because it isn't a "text"... It is binary data.

Encrypting large files (size approximately 100MB) [duplicate]

I have to encrypt, store and then later decrypt large files. What is the best way of doing that? I heard RSA encryption is expensive and was advised to use RSA to encrypt an AES key and then use the AES key to encrypt the large files. Any suggestions with example will be great.
One organism's large is another's petite, though we all know expensive when we see it. Wink, wink.
Try benchmarking something like the following in your environment and see where you're at:
EDIT 2/13/2012: The code has been updated as I've become (imperceptibly) smarter and also noticed a few cut'n'paste errors that had crept in. Mea culpa.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
...
// Rfc2898DeriveBytes constants:
public readonly byte[] salt = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Must be at least eight bytes. MAKE THIS SALTIER!
public const int iterations = 1042; // Recommendation is >= 1000.
/// <summary>Decrypt a file.</summary>
/// <remarks>NB: "Padding is invalid and cannot be removed." is the Universal CryptoServices error. Make sure the password, salt and iterations are correct before getting nervous.</remarks>
/// <param name="sourceFilename">The full path and name of the file to be decrypted.</param>
/// <param name="destinationFilename">The full path and name of the file to be output.</param>
/// <param name="password">The password for the decryption.</param>
/// <param name="salt">The salt to be applied to the password.</param>
/// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
public void DecryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
try
{
using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
catch (CryptographicException exception)
{
if (exception.Message == "Padding is invalid and cannot be removed.")
throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
else
throw;
}
}
}
}
/// <summary>Encrypt a file.</summary>
/// <param name="sourceFilename">The full path and name of the file to be encrypted.</param>
/// <param name="destinationFilename">The full path and name of the file to be output.</param>
/// <param name="password">The password for the encryption.</param>
/// <param name="salt">The salt to be applied to the password.</param>
/// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
public void EncryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);
using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
}
}
This may help
/// Encrypts a file using Rijndael algorithm.
///</summary>
///<param name="inputFile"></param>
///<param name="outputFile"></param>
private void EncryptFile(string inputFile, string outputFile)
{
try
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch
{
MessageBox.Show("Encryption failed!", "Error");
}
}
///
/// Decrypts a file using Rijndael algorithm.
///</summary>
///<param name="inputFile"></param>
///<param name="outputFile"></param>
private void DecryptFile(string inputFile, string outputFile)
{
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
}
source:
http://www.codeproject.com/Articles/26085/File-Encryption-and-Decryption-in-C
Generally the strategy you have described is used when data will be encrypted on one machine (like a server) and then decrypted by another machine (client). The server will encrypt the data using symmetric key encryption (for performance) with a newly generated key and encrypt this symmetric key with a public key (matching a client's private key). The server sends the client both the encrypted data and the encrypted symmetric key. The client can decrypt the symmetric key with it's private key and then use this symmetric key for decrypting the data.
If you are encrypting and decrypting the data on the same machine it may not make sense to use both RSA and AES as you would not be trying to pass the encryption key to another machine.
Like you heard asymmetric cryptography, like RSA, is much slower than symmetric cryptography (e.g. AES) but it does have it's advantages (simpler key management, e.g. a single private key to protect).
The key (pun intended) is to use the advantages of both (private key of asymmetric and speed of symmetric) while ignoring the inconvenience of the other (many secret keys and slow speed).
You can do this by using RSA once per file (no huge performance impact) to encrypt a (symmetric) secret key that is used to encrypt (much faster) your large file. This *wrapping of the symmetric key allows you to only manage a single, private key.
Here's a link to my old (but still true) blog post that gives an example to do this using C# and the .NET framework (Microsoft of Mono).
RSA
It's true asymmetric cryptography (RSA, ECC, etc.) is slower than symmetric (AES, ChaCha20, etc). RSA and others are great for securing a random symmetric key (or establishing one). AES and others are great for efficient encryption, used along with integrity checking (HMAC).
Importantly, mature symmetric ciphers don't have any known theoretical weakness. Unless your attackers has the symmetric key, the encryption cannot be broken. Currently, all mature asymmetric cryptography (RSA, ECC) are based on mathematical properties that are vulnerable to being cracked by a future Quantum Computer (if it ever comes).
Also, handling of public/private keys becomes a problem. It's simple for a human to remember a password - their brain cannot be hacked. With public/private keys, they need to be stored somewhere. Particularly the private key is sensitive. Computers have TDM components that can create and store public/private keys separate to the CPU. This is very complicated to use.
So with that in mind, RSA should only be used if and when it's absolutely necessary.
AES
Here is a complete version I wrote recently, that returns the wrapping streamer, so you can use it however you need.
Also, this method generates IV from random generator instead of the password digestor. This is best practice, for example 7z does this - see https://crypto.stackexchange.com/questions/61945/is-it-ok-to-transmit-an-iv-as-a-custom-http-header. The IV is included in the header for the output.
Usage:
void Save()
{
var encryptedFilePath = Directory.GetCurrentDirectory() + "\\data.bin.aes";
using(var fileStream = File.Create(encryptedFilePath))
{
using (var cryptoStream = Security.FileEncryptor.CreateEncryptor(fileStream, passwordHere))
{
var formatter = new BinaryFormatter();
formatter.Serialize(cryptoStream, myObject);
cryptoStream.Flush();
}
}
}
void Load()
{
var encryptedFilePath = Directory.GetCurrentDirectory() + "\\data.bin.aes";
using(var fileStream = File.Open(encryptedFilePath, FileMode.Open))
{
using (var cryptoStream = Security.FileEncryptor.CreateDecryptor(fileStream, passwordHere))
{
var formatter = new BinaryFormatter();
var myObject = (myObjectType)formatter.Deserialize(cryptoStream);
}
}
}
Utility:
using System.IO;
using System.Security.Cryptography;
using System;
namespace Security
{
class FileEncryptor
{
public static Stream CreateEncryptor(Stream source, string password)
{
byte[] SaltBytes = new byte[16];
RandomNumberGenerator.Fill(SaltBytes); //RandomNumberGenerator is used for .Net Core 3
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, SaltBytes, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
byte[] IVBytes = new byte[aes.BlockSize / 8];
RandomNumberGenerator.Fill(IVBytes); //RandomNumberGenerator is used for .Net Core 3
aes.IV = IVBytes;
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);
//Store/Send the Salt and IV - this can be shared. It's more important that it's very random, than being private.
source.WriteByte((byte)SaltBytes.Length);
source.Write(SaltBytes, 0, SaltBytes.Length);
source.WriteByte((byte)IVBytes.Length);
source.Write(IVBytes, 0, IVBytes.Length);
source.Flush();
var cryptoStream = new CryptoStream(source, transform, CryptoStreamMode.Write);
return cryptoStream;
}
public static Stream CreateDecryptor(Stream source, string password)
{
var ArrayLength = source.ReadByte();
if (ArrayLength == -1) throw new Exception("Salt length not found");
byte[] SaltBytes = new byte[ArrayLength];
var readBytes = source.Read(SaltBytes, 0, ArrayLength);
if (readBytes != ArrayLength) throw new Exception("No support for multiple reads");
ArrayLength = source.ReadByte();
if (ArrayLength == -1) throw new Exception("Salt length not found");
byte[] IVBytes = new byte[ArrayLength];
readBytes = source.Read(IVBytes, 0, ArrayLength);
if (readBytes != ArrayLength) throw new Exception("No support for multiple reads");
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
aes.IV = IVBytes;
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, SaltBytes, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
var cryptoStream = new CryptoStream(source, transform, CryptoStreamMode.Read);
return cryptoStream;
}
public const int iterations = 1042; // Recommendation is >= 1000.
}
}

Encrypting/Decrypting large files (.NET)

I have to encrypt, store and then later decrypt large files. What is the best way of doing that? I heard RSA encryption is expensive and was advised to use RSA to encrypt an AES key and then use the AES key to encrypt the large files. Any suggestions with example will be great.
One organism's large is another's petite, though we all know expensive when we see it. Wink, wink.
Try benchmarking something like the following in your environment and see where you're at:
EDIT 2/13/2012: The code has been updated as I've become (imperceptibly) smarter and also noticed a few cut'n'paste errors that had crept in. Mea culpa.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
...
// Rfc2898DeriveBytes constants:
public readonly byte[] salt = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Must be at least eight bytes. MAKE THIS SALTIER!
public const int iterations = 1042; // Recommendation is >= 1000.
/// <summary>Decrypt a file.</summary>
/// <remarks>NB: "Padding is invalid and cannot be removed." is the Universal CryptoServices error. Make sure the password, salt and iterations are correct before getting nervous.</remarks>
/// <param name="sourceFilename">The full path and name of the file to be decrypted.</param>
/// <param name="destinationFilename">The full path and name of the file to be output.</param>
/// <param name="password">The password for the decryption.</param>
/// <param name="salt">The salt to be applied to the password.</param>
/// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
public void DecryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
try
{
using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
catch (CryptographicException exception)
{
if (exception.Message == "Padding is invalid and cannot be removed.")
throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
else
throw;
}
}
}
}
/// <summary>Encrypt a file.</summary>
/// <param name="sourceFilename">The full path and name of the file to be encrypted.</param>
/// <param name="destinationFilename">The full path and name of the file to be output.</param>
/// <param name="password">The password for the encryption.</param>
/// <param name="salt">The salt to be applied to the password.</param>
/// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
public void EncryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);
using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
}
}
This may help
/// Encrypts a file using Rijndael algorithm.
///</summary>
///<param name="inputFile"></param>
///<param name="outputFile"></param>
private void EncryptFile(string inputFile, string outputFile)
{
try
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch
{
MessageBox.Show("Encryption failed!", "Error");
}
}
///
/// Decrypts a file using Rijndael algorithm.
///</summary>
///<param name="inputFile"></param>
///<param name="outputFile"></param>
private void DecryptFile(string inputFile, string outputFile)
{
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
}
source:
http://www.codeproject.com/Articles/26085/File-Encryption-and-Decryption-in-C
Generally the strategy you have described is used when data will be encrypted on one machine (like a server) and then decrypted by another machine (client). The server will encrypt the data using symmetric key encryption (for performance) with a newly generated key and encrypt this symmetric key with a public key (matching a client's private key). The server sends the client both the encrypted data and the encrypted symmetric key. The client can decrypt the symmetric key with it's private key and then use this symmetric key for decrypting the data.
If you are encrypting and decrypting the data on the same machine it may not make sense to use both RSA and AES as you would not be trying to pass the encryption key to another machine.
Like you heard asymmetric cryptography, like RSA, is much slower than symmetric cryptography (e.g. AES) but it does have it's advantages (simpler key management, e.g. a single private key to protect).
The key (pun intended) is to use the advantages of both (private key of asymmetric and speed of symmetric) while ignoring the inconvenience of the other (many secret keys and slow speed).
You can do this by using RSA once per file (no huge performance impact) to encrypt a (symmetric) secret key that is used to encrypt (much faster) your large file. This *wrapping of the symmetric key allows you to only manage a single, private key.
Here's a link to my old (but still true) blog post that gives an example to do this using C# and the .NET framework (Microsoft of Mono).
RSA
It's true asymmetric cryptography (RSA, ECC, etc.) is slower than symmetric (AES, ChaCha20, etc). RSA and others are great for securing a random symmetric key (or establishing one). AES and others are great for efficient encryption, used along with integrity checking (HMAC).
Importantly, mature symmetric ciphers don't have any known theoretical weakness. Unless your attackers has the symmetric key, the encryption cannot be broken. Currently, all mature asymmetric cryptography (RSA, ECC) are based on mathematical properties that are vulnerable to being cracked by a future Quantum Computer (if it ever comes).
Also, handling of public/private keys becomes a problem. It's simple for a human to remember a password - their brain cannot be hacked. With public/private keys, they need to be stored somewhere. Particularly the private key is sensitive. Computers have TDM components that can create and store public/private keys separate to the CPU. This is very complicated to use.
So with that in mind, RSA should only be used if and when it's absolutely necessary.
AES
Here is a complete version I wrote recently, that returns the wrapping streamer, so you can use it however you need.
Also, this method generates IV from random generator instead of the password digestor. This is best practice, for example 7z does this - see https://crypto.stackexchange.com/questions/61945/is-it-ok-to-transmit-an-iv-as-a-custom-http-header. The IV is included in the header for the output.
Usage:
void Save()
{
var encryptedFilePath = Directory.GetCurrentDirectory() + "\\data.bin.aes";
using(var fileStream = File.Create(encryptedFilePath))
{
using (var cryptoStream = Security.FileEncryptor.CreateEncryptor(fileStream, passwordHere))
{
var formatter = new BinaryFormatter();
formatter.Serialize(cryptoStream, myObject);
cryptoStream.Flush();
}
}
}
void Load()
{
var encryptedFilePath = Directory.GetCurrentDirectory() + "\\data.bin.aes";
using(var fileStream = File.Open(encryptedFilePath, FileMode.Open))
{
using (var cryptoStream = Security.FileEncryptor.CreateDecryptor(fileStream, passwordHere))
{
var formatter = new BinaryFormatter();
var myObject = (myObjectType)formatter.Deserialize(cryptoStream);
}
}
}
Utility:
using System.IO;
using System.Security.Cryptography;
using System;
namespace Security
{
class FileEncryptor
{
public static Stream CreateEncryptor(Stream source, string password)
{
byte[] SaltBytes = new byte[16];
RandomNumberGenerator.Fill(SaltBytes); //RandomNumberGenerator is used for .Net Core 3
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, SaltBytes, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
byte[] IVBytes = new byte[aes.BlockSize / 8];
RandomNumberGenerator.Fill(IVBytes); //RandomNumberGenerator is used for .Net Core 3
aes.IV = IVBytes;
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);
//Store/Send the Salt and IV - this can be shared. It's more important that it's very random, than being private.
source.WriteByte((byte)SaltBytes.Length);
source.Write(SaltBytes, 0, SaltBytes.Length);
source.WriteByte((byte)IVBytes.Length);
source.Write(IVBytes, 0, IVBytes.Length);
source.Flush();
var cryptoStream = new CryptoStream(source, transform, CryptoStreamMode.Write);
return cryptoStream;
}
public static Stream CreateDecryptor(Stream source, string password)
{
var ArrayLength = source.ReadByte();
if (ArrayLength == -1) throw new Exception("Salt length not found");
byte[] SaltBytes = new byte[ArrayLength];
var readBytes = source.Read(SaltBytes, 0, ArrayLength);
if (readBytes != ArrayLength) throw new Exception("No support for multiple reads");
ArrayLength = source.ReadByte();
if (ArrayLength == -1) throw new Exception("Salt length not found");
byte[] IVBytes = new byte[ArrayLength];
readBytes = source.Read(IVBytes, 0, ArrayLength);
if (readBytes != ArrayLength) throw new Exception("No support for multiple reads");
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
aes.IV = IVBytes;
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, SaltBytes, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
var cryptoStream = new CryptoStream(source, transform, CryptoStreamMode.Read);
return cryptoStream;
}
public const int iterations = 1042; // Recommendation is >= 1000.
}
}

Encrypt and decrypt a string in C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can I encrypt and decrypt a string in C#?
EDIT 2013-Oct: Although I've edited this answer over time to address shortcomings, please see jbtule's answer for a more robust, informed solution.
https://stackoverflow.com/a/10366194/188474
Original Answer:
Here's a working example derived from the "RijndaelManaged Class" documentation and the MCTS Training Kit.
EDIT 2012-April: This answer was edited to pre-pend the IV per jbtule's suggestion and as illustrated here:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx
Good luck!
public class Crypto
{
//While an app specific salt is not the best practice for
//password based encryption, it's probably safe enough as long as
//it is truly uncommon. Also too much work to alter this answer otherwise.
private static byte[] _salt = __To_Do__("Add a app specific salt here");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
Modern Examples of Symmetric Authenticated Encryption of a string.
The general best practice for symmetric encryption is to use Authenticated Encryption with Associated Data (AEAD), however this isn't a part of the standard .net crypto libraries. So the first example uses AES256 and then HMAC256, a two step Encrypt then MAC, which requires more overhead and more keys.
The second example uses the simpler practice of AES256-GCM using the open source Bouncy Castle (via nuget).
Both examples have a main function that takes secret message string, key(s) and an optional non-secret payload and return and authenticated encrypted string optionally prepended with the non-secret data. Ideally you would use these with 256bit key(s) randomly generated see NewKey().
Both examples also have a helper methods that use a string password to generate the keys. These helper methods are provided as a convenience to match up with other examples, however they are far less secure because the strength of the password is going to be far weaker than a 256 bit key.
Update:
Added byte[] overloads, and only the Gist has the full formatting with 4 spaces indent and api docs due to StackOverflow answer limits.
.NET Built-in Encrypt(AES)-Then-MAC(HMAC) [Gist]
/*
* This work (Modern Encryption of a String C#, by James Tuley),
* identified by James Tuley, is free of known copyright restrictions.
* https://gist.github.com/4336842
* http://creativecommons.org/publicdomain/mark/1.0/
*/
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Encryption
{
public static class AESThenHMAC
{
private static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create();
//Preconfigured Encryption Parameters
public static readonly int BlockBitSize = 128;
public static readonly int KeyBitSize = 256;
//Preconfigured Password Key Derivation Parameters
public static readonly int SaltBitSize = 64;
public static readonly int Iterations = 10000;
public static readonly int MinPasswordLength = 12;
/// <summary>
/// Helper that generates a random key on each call.
/// </summary>
/// <returns></returns>
public static byte[] NewKey()
{
var key = new byte[KeyBitSize / 8];
Random.GetBytes(key);
return key;
}
/// <summary>
/// Simple Encryption (AES) then Authentication (HMAC) for a UTF8 Message.
/// </summary>
/// <param name="secretMessage">The secret message.</param>
/// <param name="cryptKey">The crypt key.</param>
/// <param name="authKey">The auth key.</param>
/// <param name="nonSecretPayload">(Optional) Non-Secret Payload.</param>
/// <returns>
/// Encrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Secret Message Required!;secretMessage</exception>
/// <remarks>
/// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize + HMac-Tag(32)) * 1.33 Base64
/// </remarks>
public static string SimpleEncrypt(string secretMessage, byte[] cryptKey, byte[] authKey,
byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(secretMessage))
throw new ArgumentException("Secret Message Required!", "secretMessage");
var plainText = Encoding.UTF8.GetBytes(secretMessage);
var cipherText = SimpleEncrypt(plainText, cryptKey, authKey, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
/// <summary>
/// Simple Authentication (HMAC) then Decryption (AES) for a secrets UTF8 Message.
/// </summary>
/// <param name="encryptedMessage">The encrypted message.</param>
/// <param name="cryptKey">The crypt key.</param>
/// <param name="authKey">The auth key.</param>
/// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
/// <returns>
/// Decrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Encrypted Message Required!;encryptedMessage</exception>
public static string SimpleDecrypt(string encryptedMessage, byte[] cryptKey, byte[] authKey,
int nonSecretPayloadLength = 0)
{
if (string.IsNullOrWhiteSpace(encryptedMessage))
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cipherText = Convert.FromBase64String(encryptedMessage);
var plainText = SimpleDecrypt(cipherText, cryptKey, authKey, nonSecretPayloadLength);
return plainText == null ? null : Encoding.UTF8.GetString(plainText);
}
/// <summary>
/// Simple Encryption (AES) then Authentication (HMAC) of a UTF8 message
/// using Keys derived from a Password (PBKDF2).
/// </summary>
/// <param name="secretMessage">The secret message.</param>
/// <param name="password">The password.</param>
/// <param name="nonSecretPayload">The non secret payload.</param>
/// <returns>
/// Encrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">password</exception>
/// <remarks>
/// Significantly less secure than using random binary keys.
/// Adds additional non secret payload for key generation parameters.
/// </remarks>
public static string SimpleEncryptWithPassword(string secretMessage, string password,
byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(secretMessage))
throw new ArgumentException("Secret Message Required!", "secretMessage");
var plainText = Encoding.UTF8.GetBytes(secretMessage);
var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
/// <summary>
/// Simple Authentication (HMAC) and then Descryption (AES) of a UTF8 Message
/// using keys derived from a password (PBKDF2).
/// </summary>
/// <param name="encryptedMessage">The encrypted message.</param>
/// <param name="password">The password.</param>
/// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
/// <returns>
/// Decrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Encrypted Message Required!;encryptedMessage</exception>
/// <remarks>
/// Significantly less secure than using random binary keys.
/// </remarks>
public static string SimpleDecryptWithPassword(string encryptedMessage, string password,
int nonSecretPayloadLength = 0)
{
if (string.IsNullOrWhiteSpace(encryptedMessage))
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cipherText = Convert.FromBase64String(encryptedMessage);
var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);
return plainText == null ? null : Encoding.UTF8.GetString(plainText);
}
public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)
{
//User Error Checks
if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey");
if (authKey == null || authKey.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey");
if (secretMessage == null || secretMessage.Length < 1)
throw new ArgumentException("Secret Message Required!", "secretMessage");
//non-secret payload optional
nonSecretPayload = nonSecretPayload ?? new byte[] { };
byte[] cipherText;
byte[] iv;
using (var aes = new AesManaged
{
KeySize = KeyBitSize,
BlockSize = BlockBitSize,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
})
{
//Use random IV
aes.GenerateIV();
iv = aes.IV;
using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
using (var cipherStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
using (var binaryWriter = new BinaryWriter(cryptoStream))
{
//Encrypt Data
binaryWriter.Write(secretMessage);
}
cipherText = cipherStream.ToArray();
}
}
//Assemble encrypted message and add authentication
using (var hmac = new HMACSHA256(authKey))
using (var encryptedStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(encryptedStream))
{
//Prepend non-secret payload if any
binaryWriter.Write(nonSecretPayload);
//Prepend IV
binaryWriter.Write(iv);
//Write Ciphertext
binaryWriter.Write(cipherText);
binaryWriter.Flush();
//Authenticate all data
var tag = hmac.ComputeHash(encryptedStream.ToArray());
//Postpend tag
binaryWriter.Write(tag);
}
return encryptedStream.ToArray();
}
}
public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)
{
//Basic Usage Error Checks
if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("CryptKey needs to be {0} bit!", KeyBitSize), "cryptKey");
if (authKey == null || authKey.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("AuthKey needs to be {0} bit!", KeyBitSize), "authKey");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
using (var hmac = new HMACSHA256(authKey))
{
var sentTag = new byte[hmac.HashSize / 8];
//Calculate Tag
var calcTag = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);
var ivLength = (BlockBitSize / 8);
//if message length is to small just return null
if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)
return null;
//Grab Sent Tag
Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);
//Compare Tag with constant time comparison
var compare = 0;
for (var i = 0; i < sentTag.Length; i++)
compare |= sentTag[i] ^ calcTag[i];
//if message doesn't authenticate return null
if (compare != 0)
return null;
using (var aes = new AesManaged
{
KeySize = KeyBitSize,
BlockSize = BlockBitSize,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
})
{
//Grab IV from message
var iv = new byte[ivLength];
Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);
using (var decrypter = aes.CreateDecryptor(cryptKey, iv))
using (var plainTextStream = new MemoryStream())
{
using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))
using (var binaryWriter = new BinaryWriter(decrypterStream))
{
//Decrypt Cipher Text from Message
binaryWriter.Write(
encryptedMessage,
nonSecretPayloadLength + iv.Length,
encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length
);
}
//Return Plain Text
return plainTextStream.ToArray();
}
}
}
}
public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)
{
nonSecretPayload = nonSecretPayload ?? new byte[] {};
//User Error Checks
if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (secretMessage == null || secretMessage.Length ==0)
throw new ArgumentException("Secret Message Required!", "secretMessage");
var payload = new byte[((SaltBitSize / 8) * 2) + nonSecretPayload.Length];
Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);
int payloadIndex = nonSecretPayload.Length;
byte[] cryptKey;
byte[] authKey;
//Use Random Salt to prevent pre-generated weak password attacks.
using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations))
{
var salt = generator.Salt;
//Generate Keys
cryptKey = generator.GetBytes(KeyBitSize / 8);
//Create Non Secret Payload
Array.Copy(salt, 0, payload, payloadIndex, salt.Length);
payloadIndex += salt.Length;
}
//Deriving separate key, might be less efficient than using HKDF,
//but now compatible with RNEncryptor which had a very similar wireformat and requires less code than HKDF.
using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations))
{
var salt = generator.Salt;
//Generate Keys
authKey = generator.GetBytes(KeyBitSize / 8);
//Create Rest of Non Secret Payload
Array.Copy(salt, 0, payload, payloadIndex, salt.Length);
}
return SimpleEncrypt(secretMessage, cryptKey, authKey, payload);
}
public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)
{
//User Error Checks
if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cryptSalt = new byte[SaltBitSize / 8];
var authSalt = new byte[SaltBitSize / 8];
//Grab Salt from Non-Secret Payload
Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length);
Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length);
byte[] cryptKey;
byte[] authKey;
//Generate crypt key
using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations))
{
cryptKey = generator.GetBytes(KeyBitSize / 8);
}
//Generate auth key
using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations))
{
authKey = generator.GetBytes(KeyBitSize / 8);
}
return SimpleDecrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength);
}
}
}
Bouncy Castle AES-GCM [Gist]
/*
* This work (Modern Encryption of a String C#, by James Tuley),
* identified by James Tuley, is free of known copyright restrictions.
* https://gist.github.com/4336842
* http://creativecommons.org/publicdomain/mark/1.0/
*/
using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
namespace Encryption
{
public static class AESGCM
{
private static readonly SecureRandom Random = new SecureRandom();
//Preconfigured Encryption Parameters
public static readonly int NonceBitSize = 128;
public static readonly int MacBitSize = 128;
public static readonly int KeyBitSize = 256;
//Preconfigured Password Key Derivation Parameters
public static readonly int SaltBitSize = 128;
public static readonly int Iterations = 10000;
public static readonly int MinPasswordLength = 12;
/// <summary>
/// Helper that generates a random new key on each call.
/// </summary>
/// <returns></returns>
public static byte[] NewKey()
{
var key = new byte[KeyBitSize / 8];
Random.NextBytes(key);
return key;
}
/// <summary>
/// Simple Encryption And Authentication (AES-GCM) of a UTF8 string.
/// </summary>
/// <param name="secretMessage">The secret message.</param>
/// <param name="key">The key.</param>
/// <param name="nonSecretPayload">Optional non-secret payload.</param>
/// <returns>
/// Encrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Secret Message Required!;secretMessage</exception>
/// <remarks>
/// Adds overhead of (Optional-Payload + BlockSize(16) + Message + HMac-Tag(16)) * 1.33 Base64
/// </remarks>
public static string SimpleEncrypt(string secretMessage, byte[] key, byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(secretMessage))
throw new ArgumentException("Secret Message Required!", "secretMessage");
var plainText = Encoding.UTF8.GetBytes(secretMessage);
var cipherText = SimpleEncrypt(plainText, key, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
/// <summary>
/// Simple Decryption & Authentication (AES-GCM) of a UTF8 Message
/// </summary>
/// <param name="encryptedMessage">The encrypted message.</param>
/// <param name="key">The key.</param>
/// <param name="nonSecretPayloadLength">Length of the optional non-secret payload.</param>
/// <returns>Decrypted Message</returns>
public static string SimpleDecrypt(string encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)
{
if (string.IsNullOrEmpty(encryptedMessage))
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cipherText = Convert.FromBase64String(encryptedMessage);
var plainText = SimpleDecrypt(cipherText, key, nonSecretPayloadLength);
return plainText == null ? null : Encoding.UTF8.GetString(plainText);
}
/// <summary>
/// Simple Encryption And Authentication (AES-GCM) of a UTF8 String
/// using key derived from a password (PBKDF2).
/// </summary>
/// <param name="secretMessage">The secret message.</param>
/// <param name="password">The password.</param>
/// <param name="nonSecretPayload">The non secret payload.</param>
/// <returns>
/// Encrypted Message
/// </returns>
/// <remarks>
/// Significantly less secure than using random binary keys.
/// Adds additional non secret payload for key generation parameters.
/// </remarks>
public static string SimpleEncryptWithPassword(string secretMessage, string password,
byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(secretMessage))
throw new ArgumentException("Secret Message Required!", "secretMessage");
var plainText = Encoding.UTF8.GetBytes(secretMessage);
var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
/// <summary>
/// Simple Decryption and Authentication (AES-GCM) of a UTF8 message
/// using a key derived from a password (PBKDF2)
/// </summary>
/// <param name="encryptedMessage">The encrypted message.</param>
/// <param name="password">The password.</param>
/// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
/// <returns>
/// Decrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Encrypted Message Required!;encryptedMessage</exception>
/// <remarks>
/// Significantly less secure than using random binary keys.
/// </remarks>
public static string SimpleDecryptWithPassword(string encryptedMessage, string password,
int nonSecretPayloadLength = 0)
{
if (string.IsNullOrWhiteSpace(encryptedMessage))
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cipherText = Convert.FromBase64String(encryptedMessage);
var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);
return plainText == null ? null : Encoding.UTF8.GetString(plainText);
}
public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null)
{
//User Error Checks
if (key == null || key.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
if (secretMessage == null || secretMessage.Length == 0)
throw new ArgumentException("Secret Message Required!", "secretMessage");
//Non-secret Payload Optional
nonSecretPayload = nonSecretPayload ?? new byte[] { };
//Using random nonce large enough not to repeat
var nonce = new byte[NonceBitSize / 8];
Random.NextBytes(nonce, 0, nonce.Length);
var cipher = new GcmBlockCipher(new AesFastEngine());
var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
cipher.Init(true, parameters);
//Generate Cipher Text With Auth Tag
var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)];
var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);
cipher.DoFinal(cipherText, len);
//Assemble Message
using (var combinedStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(combinedStream))
{
//Prepend Authenticated Payload
binaryWriter.Write(nonSecretPayload);
//Prepend Nonce
binaryWriter.Write(nonce);
//Write Cipher Text
binaryWriter.Write(cipherText);
}
return combinedStream.ToArray();
}
}
public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)
{
//User Error Checks
if (key == null || key.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
using (var cipherStream = new MemoryStream(encryptedMessage))
using (var cipherReader = new BinaryReader(cipherStream))
{
//Grab Payload
var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);
//Grab Nonce
var nonce = cipherReader.ReadBytes(NonceBitSize / 8);
var cipher = new GcmBlockCipher(new AesFastEngine());
var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
cipher.Init(false, parameters);
//Decrypt Cipher Text
var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length);
var plainText = new byte[cipher.GetOutputSize(cipherText.Length)];
try
{
var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
cipher.DoFinal(plainText, len);
}
catch (InvalidCipherTextException)
{
//Return null if it doesn't authenticate
return null;
}
return plainText;
}
}
public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)
{
nonSecretPayload = nonSecretPayload ?? new byte[] {};
//User Error Checks
if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (secretMessage == null || secretMessage.Length == 0)
throw new ArgumentException("Secret Message Required!", "secretMessage");
var generator = new Pkcs5S2ParametersGenerator();
//Use Random Salt to minimize pre-generated weak password attacks.
var salt = new byte[SaltBitSize / 8];
Random.NextBytes(salt);
generator.Init(
PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),
salt,
Iterations);
//Generate Key
var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);
//Create Full Non Secret Payload
var payload = new byte[salt.Length + nonSecretPayload.Length];
Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);
Array.Copy(salt,0, payload,nonSecretPayload.Length, salt.Length);
return SimpleEncrypt(secretMessage, key.GetKey(), payload);
}
public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)
{
//User Error Checks
if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var generator = new Pkcs5S2ParametersGenerator();
//Grab Salt from Payload
var salt = new byte[SaltBitSize / 8];
Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length);
generator.Init(
PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),
salt,
Iterations);
//Generate Key
var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);
return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength);
}
}
}
Here is an example using RSA.
Important: There is a limit to the size of data you can encrypt with the RSA encryption, KeySize - MinimumPadding. e.g. 256 bytes (assuming 2048 bit key) - 42 bytes (min OEAP padding) = 214 bytes (max plaintext size)
Replace your_rsa_key with your RSA key.
var provider = new System.Security.Cryptography.RSACryptoServiceProvider();
provider.ImportParameters(your_rsa_key);
var encryptedBytes = provider.Encrypt(
System.Text.Encoding.UTF8.GetBytes("Hello World!"), true);
string decryptedTest = System.Text.Encoding.UTF8.GetString(
provider.Decrypt(encryptedBytes, true));
For more info, visit MSDN - RSACryptoServiceProvider
If you are using ASP.Net you can now use built in functionality in .Net 4.0 onwards.
System.Web.Security.MachineKey
.Net 4.5 has MachineKey.Protect() and MachineKey.Unprotect().
.Net 4.0 has MachineKey.Encode() and MachineKey.Decode(). You should just set the MachineKeyProtection to 'All'.
Outside of ASP.Net this class seems to generate a new key with every app restart so doesn't work. With a quick peek in ILSpy it looks to me like it generates its own defaults if the appropriate app.settings are missing. So you may actually be able to set it up outside ASP.Net.
I haven't been able to find a non-ASP.Net equivalent outside the System.Web namespace.
BouncyCastle is a great Crypto library for .NET, it's available as a Nuget package for install into your projects. I like it a lot more than what's currently available in the System.Security.Cryptography library. It gives you a lot more options in terms of available algorithms, and provides more modes for those algorithms.
This is an example of an implementation of TwoFish, which was written by Bruce Schneier (hero to all us paranoid people out there). It's a symmetric algorithm like the Rijndael
(aka AES). It was one of the three finalists for the AES standard and sibling to another famous algorithm written by Bruce Schneier called BlowFish.
First thing with bouncycastle is to create an encryptor class, this will make it easier to implement other block ciphers within the library. The following encryptor class takes in a generic argument T where T implements IBlockCipher and has a default constructor.
UPDATE: Due to popular demand I have decided to implement generating a random IV as well as include an HMAC into this class. Although from a style perspective this goes against the SOLID principle of single responsibility, because of the nature of what this class does I reniged. This class will now take two generic parameters, one for the cipher and one for the digest. It automatically generates the IV using RNGCryptoServiceProvider to provide good RNG entropy, and allows you to use whatever digest algorithm you want from BouncyCastle to generate the MAC.
using System;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
public sealed class Encryptor<TBlockCipher, TDigest>
where TBlockCipher : IBlockCipher, new()
where TDigest : IDigest, new()
{
private Encoding encoding;
private IBlockCipher blockCipher;
private BufferedBlockCipher cipher;
private HMac mac;
private byte[] key;
public Encryptor(Encoding encoding, byte[] key, byte[] macKey)
{
this.encoding = encoding;
this.key = key;
this.Init(key, macKey, new Pkcs7Padding());
}
public Encryptor(Encoding encoding, byte[] key, byte[] macKey, IBlockCipherPadding padding)
{
this.encoding = encoding;
this.key = key;
this.Init(key, macKey, padding);
}
private void Init(byte[] key, byte[] macKey, IBlockCipherPadding padding)
{
this.blockCipher = new CbcBlockCipher(new TBlockCipher());
this.cipher = new PaddedBufferedBlockCipher(this.blockCipher, padding);
this.mac = new HMac(new TDigest());
this.mac.Init(new KeyParameter(macKey));
}
public string Encrypt(string plain)
{
return Convert.ToBase64String(EncryptBytes(plain));
}
public byte[] EncryptBytes(string plain)
{
byte[] input = this.encoding.GetBytes(plain);
var iv = this.GenerateIV();
var cipher = this.BouncyCastleCrypto(true, input, new ParametersWithIV(new KeyParameter(key), iv));
byte[] message = CombineArrays(iv, cipher);
this.mac.Reset();
this.mac.BlockUpdate(message, 0, message.Length);
byte[] digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];
this.mac.DoFinal(digest, 0);
var result = CombineArrays(digest, message);
return result;
}
public byte[] DecryptBytes(byte[] bytes)
{
// split the digest into component parts
var digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];
var message = new byte[bytes.Length - digest.Length];
var iv = new byte[this.blockCipher.GetBlockSize()];
var cipher = new byte[message.Length - iv.Length];
Buffer.BlockCopy(bytes, 0, digest, 0, digest.Length);
Buffer.BlockCopy(bytes, digest.Length, message, 0, message.Length);
if (!IsValidHMac(digest, message))
{
throw new CryptoException();
}
Buffer.BlockCopy(message, 0, iv, 0, iv.Length);
Buffer.BlockCopy(message, iv.Length, cipher, 0, cipher.Length);
byte[] result = this.BouncyCastleCrypto(false, cipher, new ParametersWithIV(new KeyParameter(key), iv));
return result;
}
public string Decrypt(byte[] bytes)
{
return this.encoding.GetString(DecryptBytes(bytes));
}
public string Decrypt(string cipher)
{
return this.Decrypt(Convert.FromBase64String(cipher));
}
private bool IsValidHMac(byte[] digest, byte[] message)
{
this.mac.Reset();
this.mac.BlockUpdate(message, 0, message.Length);
byte[] computed = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];
this.mac.DoFinal(computed, 0);
return AreEqual(digest,computed);
}
private static bool AreEqual(byte [] digest, byte[] computed)
{
if(digest.Length != computed.Length)
{
return false;
}
int result = 0;
for (int i = 0; i < digest.Length; i++)
{
// compute equality of all bytes before returning.
// helps prevent timing attacks:
// https://codahale.com/a-lesson-in-timing-attacks/
result |= digest[i] ^ computed[i];
}
return result == 0;
}
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, ICipherParameters parameters)
{
try
{
cipher.Init(forEncrypt, parameters);
return this.cipher.DoFinal(input);
}
catch (CryptoException)
{
throw;
}
}
private byte[] GenerateIV()
{
using (var provider = new RNGCryptoServiceProvider())
{
// 1st block
byte[] result = new byte[this.blockCipher.GetBlockSize()];
provider.GetBytes(result);
return result;
}
}
private static byte[] CombineArrays(byte[] source1, byte[] source2)
{
byte[] result = new byte[source1.Length + source2.Length];
Buffer.BlockCopy(source1, 0, result, 0, source1.Length);
Buffer.BlockCopy(source2, 0, result, source1.Length, source2.Length);
return result;
}
}
Next just call the encrypt and decrypt methods on the new class, here's the example using twofish:
var encrypt = new Encryptor<TwofishEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);
string cipher = encrypt.Encrypt("TEST");
string plainText = encrypt.Decrypt(cipher);
It's just as easy to substitute another block cipher like TripleDES:
var des = new Encryptor<DesEdeEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);
string cipher = des.Encrypt("TEST");
string plainText = des.Decrypt(cipher);
Finally if you want to use AES with SHA256 HMAC you can do the following:
var aes = new Encryptor<AesEngine, Sha256Digest>(Encoding.UTF8, key, hmacKey);
cipher = aes.Encrypt("TEST");
plainText = aes.Decrypt(cipher);
The hardest part about encryption actually deals with the keys and not the algorithms. You'll have to think about where you store your keys, and if you have to, how you exchange them. These algorithms have all withstood the test of time, and are extremely hard to break. Someone who wants to steal information from you isn't going to spend eternity doing cryptanalysis on your messages, they're going to try to figure out what or where your key is. So #1 choose your keys wisely, #2 store them in a safe place, if you use a web.config and IIS then you can encrypt parts of the the web.config, and finally if you have to exchange keys make sure that your protocol for exchanging the key is secure.
Update 2
Changed compare method to mitigate against timing attacks. See more info here http://codahale.com/a-lesson-in-timing-attacks/ . Also updated to default to PKCS7 padding and added new constructor to allow end user the ability to choose which padding they would like to use. Thanks #CodesInChaos for the suggestions.
Disclaimer: This solution should only be used for data at rest that is not exposed to the public (for example - a configuration file or DB). Only in this scenario, the quick-and-dirty solution can be considered better than #jbtule's solution, due to lower maintanance.
Original post:
I found jbtule's answer a bit complicated for a quick and dirty secured AES string encryption and Brett's answer had a bug with the Initialization Vector being a fixed value making it vulnerable to padding attacks, so I fixed Brett's code and added a random IV that is added to the chipered string, creating a different encrypted value each and every encryption of the same value:
Encryption:
public static string Encrypt(string clearText)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
byte[] IV = new byte[15];
rand.NextBytes(IV);
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(IV) + Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
Decryption:
public static string Decrypt(string cipherText)
{
byte[] IV = Convert.FromBase64String(cipherText.Substring(0, 20));
cipherText = cipherText.Substring(20).Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
Replace EncryptionKey with your key.
In my implementation, the key is being saved in the configuration file (web.config\app.config) as you shouldn't save it hard coded. The configuration file should be also encrypted so the key won't be saved as clear text in it.
protected static string _Key = "";
protected static string EncryptionKey
{
get
{
if (String.IsNullOrEmpty(_Key))
{
_Key = ConfigurationManager.AppSettings["AESKey"].ToString();
}
return _Key;
}
}
Encryption
public string EncryptString(string inputString)
{
MemoryStream memStream = null;
try
{
byte[] key = { };
byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };
string encryptKey = "aXb2uy4z"; // MUST be 8 characters
key = Encoding.UTF8.GetBytes(encryptKey);
byte[] byteInput = Encoding.UTF8.GetBytes(inputString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
memStream = new MemoryStream();
ICryptoTransform transform = provider.CreateEncryptor(key, IV);
CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
cryptoStream.Write(byteInput, 0, byteInput.Length);
cryptoStream.FlushFinalBlock();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return Convert.ToBase64String(memStream.ToArray());
}
Decryption:
public string DecryptString(string inputString)
{
MemoryStream memStream = null;
try
{
byte[] key = { };
byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };
string encryptKey = "aXb2uy4z"; // MUST be 8 characters
key = Encoding.UTF8.GetBytes(encryptKey);
byte[] byteInput = new byte[inputString.Length];
byteInput = Convert.FromBase64String(inputString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
memStream = new MemoryStream();
ICryptoTransform transform = provider.CreateDecryptor(key, IV);
CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
cryptoStream.Write(byteInput, 0, byteInput.Length);
cryptoStream.FlushFinalBlock();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Encoding encoding1 = Encoding.UTF8;
return encoding1.GetString(memStream.ToArray());
}
The following example demonstrates how to encrypt and decrypt sample data:
// This constant is used to determine the keysize of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private const int Keysize = 128;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 1000;
public static string Encrypt(string plainText, string passPhrase)
{
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = GenerateBitsOfRandomEntropy(16);
var ivStringBytes = GenerateBitsOfRandomEntropy(16);
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
public static string Decrypt(string cipherText, string passPhrase)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
private static byte[] GenerateBitsOfRandomEntropy(int size)
{
// 32 Bytes will give us 256 bits.
// 16 Bytes will give us 128 bits.
var randomBytes = new byte[size];
using (var rngCsp = new RNGCryptoServiceProvider())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
With the reference of Encrypt and Decrypt a String in c#, I found one of good solution :
static readonly string PasswordHash = "P##Sw0rd";
static readonly string SaltKey = "S#LT&KEY";
static readonly string VIKey = "#1B2c3D4e5F6g7H8";
For Encrypt
public static string Encrypt(string plainText)
{
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
byte[] cipherTextBytes;
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
cryptoStream.Close();
}
memoryStream.Close();
}
return Convert.ToBase64String(cipherTextBytes);
}
For Decrypt
public static string Decrypt(string encryptedText)
{
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
var memoryStream = new MemoryStream(cipherTextBytes);
var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
}
To support mattmanser answer. Here's an example using MachineKey class to encrypt/decrypt URL safe values.
Something to bear in mind, as mentioned before, this will use Machine config settings (https://msdn.microsoft.com/en-us/library/ff649308.aspx). You can set encryption and decryption key/algorithm manually (you might need this specially if your site is running on multiple servers) in web.config file. You can generate keys from IIS (see here: https://blogs.msdn.microsoft.com/vijaysk/2009/05/13/iis-7-tip-10-you-can-generate-machine-keys-from-the-iis-manager/) or can use an online machine key generator like: http://www.developerfusion.com/tools/generatemachinekey/
private static readonly UTF8Encoding Encoder = new UTF8Encoding();
public static string Encrypt(string unencrypted)
{
if (string.IsNullOrEmpty(unencrypted))
return string.Empty;
try
{
var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));
if (encryptedBytes != null && encryptedBytes.Length > 0)
return HttpServerUtility.UrlTokenEncode(encryptedBytes);
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
public static string Decrypt(string encrypted)
{
if (string.IsNullOrEmpty(encrypted))
return string.Empty;
try
{
var bytes = HttpServerUtility.UrlTokenDecode(encrypted);
if (bytes != null && bytes.Length > 0)
{
var decryptedBytes = MachineKey.Unprotect(bytes);
if(decryptedBytes != null && decryptedBytes.Length > 0)
return Encoder.GetString(decryptedBytes);
}
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
Here is a simple example of encrypting strings in C# using AES CBC mode with random IV and HMAC and password-derived keys, to show the basic moving parts:
private byte[] EncryptBytes(byte[] key, byte[] plaintext)
{
using (var cipher = new RijndaelManaged { Key = key })
{
using (var encryptor = cipher.CreateEncryptor())
{
var ciphertext = encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length);
// IV is prepended to ciphertext
return cipher.IV.Concat(ciphertext).ToArray();
}
}
}
private byte[] DecryptBytes(byte[] key, byte[] packed)
{
using (var cipher = new RijndaelManaged { Key = key })
{
int ivSize = cipher.BlockSize / 8;
cipher.IV = packed.Take(ivSize).ToArray();
using (var encryptor = cipher.CreateDecryptor())
{
return encryptor.TransformFinalBlock(packed, ivSize, packed.Length - ivSize);
}
}
}
private byte[] AddMac(byte[] key, byte[] data)
{
using (var hmac = new HMACSHA256(key))
{
var macBytes = hmac.ComputeHash(data);
// HMAC is appended to data
return data.Concat(macBytes).ToArray();
}
}
private bool BadMac(byte[] found, byte[] computed)
{
int mismatch = 0;
// Aim for consistent timing regardless of inputs
for (int i = 0; i < found.Length; i++)
{
mismatch += found[i] == computed[i] ? 0 : 1;
}
return mismatch != 0;
}
private byte[] RemoveMac(byte[] key, byte[] data)
{
using (var hmac = new HMACSHA256(key))
{
int macSize = hmac.HashSize / 8;
var packed = data.Take(data.Length - macSize).ToArray();
var foundMac = data.Skip(packed.Length).ToArray();
var computedMac = hmac.ComputeHash(packed);
if (this.BadMac(foundMac, computedMac))
{
throw new Exception("Bad MAC");
}
return packed;
}
}
private List<byte[]> DeriveTwoKeys(string password)
{
var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var kdf = new Rfc2898DeriveBytes(password, salt, 10000);
var bytes = kdf.GetBytes(32); // Two keys 128 bits each
return new List<byte[]> { bytes.Take(16).ToArray(), bytes.Skip(16).ToArray() };
}
public byte[] EncryptString(string password, String message)
{
var keys = this.DeriveTwoKeys(password);
var plaintext = Encoding.UTF8.GetBytes(message);
var packed = this.EncryptBytes(keys[0], plaintext);
return this.AddMac(keys[1], packed);
}
public String DecryptString(string password, byte[] secret)
{
var keys = this.DeriveTwoKeys(password);
var packed = this.RemoveMac(keys[1], secret);
var plaintext = this.DecryptBytes(keys[0], packed);
return Encoding.UTF8.GetString(plaintext);
}
public void Example()
{
var password = "correcthorsebatterystaple";
var secret = this.EncryptString(password, "Hello World");
Console.WriteLine("secret: " + BitConverter.ToString(secret));
var recovered = this.DecryptString(password, secret);
Console.WriteLine(recovered);
}
An alternative to BouncyCastle for AES-GCM encryption is libsodium-net. It wraps the libsodium C library. One nice advantage is that it uses the AES-NI extension in CPUs for very fast encryption. The down side is that it won't work at all if the CPU doesn't have the extension. There's no software fall back.
The following code is an improved version of Ghazal's answer to a similar question.
public class EncryptionHelper
{
private Aes aesEncryptor;
public EncryptionHelper()
{
}
private void BuildAesEncryptor(string key)
{
aesEncryptor = Aes.Create();
var pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
aesEncryptor.Key = pdb.GetBytes(32);
aesEncryptor.IV = pdb.GetBytes(16);
}
public string EncryptString(string clearText, string key)
{
BuildAesEncryptor(key);
var clearBytes = Encoding.Unicode.GetBytes(clearText);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, aesEncryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
}
var encryptedText = Convert.ToBase64String(ms.ToArray());
return encryptedText;
}
}
public string DecryptString(string cipherText, string key)
{
BuildAesEncryptor(key);
cipherText = cipherText.Replace(" ", "+");
var cipherBytes = Convert.FromBase64String(cipherText);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, aesEncryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
}
var clearText = Encoding.Unicode.GetString(ms.ToArray());
return clearText;
}
}
}
This is the class that was placed here by Brett. However I made a slight edit since I was receiving the error 'Invalid length for a Base-64 char array' when using it for URL strings to encrypt and decrypt.
public class CryptoURL
{
private static byte[] _salt = Encoding.ASCII.GetBytes("Catto_Salt_Enter_Any_Value99");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// The SharedSecret for the Password Reset that is used is in the next line
/// string sharedSecret = "OneUpSharedSecret9";
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptString(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = HttpServerUtility.UrlTokenEncode(msEncrypt.ToArray());
//outStr = Convert.ToBase64String(msEncrypt.ToArray());
// you may need to add a reference. right click reference in solution explorer => "add Reference" => .NET tab => select "System.Web"
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptString(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
byte[] inputByteArray;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
//byte[] bytes = Convert.FromBase64String(cipherText);
inputByteArray = HttpServerUtility.UrlTokenDecode(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(inputByteArray))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
catch (System.Exception ex)
{
return "ERROR";
//throw ex;
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
static string ConvertStringArrayToString(string[] array)
{
//
// Concatenate all the elements into a StringBuilder.
//
StringBuilder builder = new StringBuilder();
foreach (string value in array)
{
builder.Append(value);
builder.Append('.');
}
return builder.ToString();
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
var key = Encoding.UTF8.GetBytes("SUkbqO2ycDo7QwpR25kfgmC7f8CoyrZy");
var data = Encoding.UTF8.GetBytes("testData");
//Encrypt data
var encrypted = CryptoHelper.EncryptData(data,key);
//Decrypt data
var decrypted = CryptoHelper.DecryptData(encrypted,key);
//Display result
Console.WriteLine(Encoding.UTF8.GetString(decrypted));
}
}
public static class CryptoHelper
{
public static byte[] EncryptData(byte[] data, byte[] key)
{
using (var aesAlg = Aes.Create())
{
aesAlg.Mode = CipherMode.CBC;
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
{
using (var msEncrypt = new MemoryStream())
{
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
csEncrypt.Write(data, 0, data.Length);
return msEncrypt.ToArray();
}
}
}
}
public static byte[] DecryptData(byte[] encrypted, byte[] key)
{
var iv = new byte[16];
Buffer.BlockCopy(encrypted, 0, iv, 0, iv.Length);
using (var aesAlg = Aes.Create())
{
aesAlg.Mode = CipherMode.CBC;
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
{
using (var msDecrypt = new MemoryStream(encrypted, iv.Length, encrypted.Length - iv.Length))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var resultStream = new MemoryStream())
{
csDecrypt.CopyTo(resultStream);
return resultStream.ToArray();
}
}
}
}
}
}
}
Good example how to do this using PGPCore with BouncyCastle, very simple solution: https://blog.bitscry.com/2018/07/05/pgp-encryption-and-decryption-in-c/
I tried different solutions but this works best for me, some have bugs but this is perfect for me.
using (PGP pgp = new PGP())
{
// Generate keys
pgp.GenerateKey(#"C:\TEMP\keys\public.asc", #"C:\TEMP\keys\private.asc", "email#email.com", "password");
// Encrypt file
pgp.EncryptFile(#"C:\TEMP\keys\content.txt", #"C:\TEMP\keys\content__encrypted.pgp", #"C:\TEMP\keys\public.asc", true, true);
// Encrypt and sign file
pgp.EncryptFileAndSign(#"C:\TEMP\keys\content.txt", #"C:\TEMP\keys\content__encrypted_signed.pgp", #"C:\TEMP\keys\public.asc", #"C:\TEMP\keys\private.asc", "password", true, true);
// Decrypt file
pgp.DecryptFile(#"C:\TEMP\keys\content__encrypted.pgp", #"C:\TEMP\keys\content__decrypted.txt", #"C:\TEMP\keys\private.asc", "password");
// Decrypt signed file
pgp.DecryptFile(#"C:\TEMP\keys\content__encrypted_signed.pgp", #"C:\TEMP\keys\content__decrypted_signed.txt", #"C:\TEMP\keys\private.asc", "password");
// Encrypt stream
using (FileStream inputFileStream = new FileStream(#"C:\TEMP\keys\content.txt", FileMode.Open))
using (Stream outputFileStream = File.Create(#"C:\TEMP\keys\content__encrypted2.pgp"))
using (Stream publicKeyStream = new FileStream(#"C:\TEMP\keys\public.asc", FileMode.Open))
pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true);
// Decrypt stream
using (FileStream inputFileStream = new FileStream(#"C:\TEMP\keys\content__encrypted2.pgp", FileMode.Open))
using (Stream outputFileStream = File.Create(#"C:\TEMP\keys\content__decrypted2.txt"))
using (Stream privateKeyStream = new FileStream(#"C:\TEMP\keys\private.asc", FileMode.Open))
pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, "password");
}
Encryption is a very common matter in programming. I think it is better to install a package to do the task for you. Maybe a simple open source NuGet project like
Simple Aes Encryption
The key is in the config file and therefore it is easy to change in the production environment, and I don't see any drawbacks.
<MessageEncryption>
<EncryptionKey KeySize="256" Key="3q2+796tvu/erb7v3q2+796tvu/erb7v3q2+796tvu8="/>
</MessageEncryption>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Text;
/// <summary>
/// Summary description for Encryption
/// </summary>
public class Encryption
{
public TripleDES CreateDES(string key)
{
MD5 md5 = new MD5CryptoServiceProvider();
TripleDES des = new TripleDESCryptoServiceProvider();
des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
des.IV = new byte[des.BlockSize / 8];
return des;
}
public byte[] Encryptiondata(string PlainText)
{
TripleDES des = CreateDES("DreamMLMKey");
ICryptoTransform ct = des.CreateEncryptor();
byte[] input = Encoding.Unicode.GetBytes(PlainText);
return ct.TransformFinalBlock(input, 0, input.Length);
}
public string Decryptiondata(string CypherText)
{
string stringToDecrypt = CypherText.Replace(" ", "+");
int len = stringToDecrypt.Length;
byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt);
byte[] b = Convert.FromBase64String(CypherText);
TripleDES des = CreateDES("DreamMLMKey");
ICryptoTransform ct = des.CreateDecryptor();
byte[] output = ct.TransformFinalBlock(b, 0, b.Length);
return Encoding.Unicode.GetString(output);
}
public string Decryptiondataurl(string CypherText)
{
string newcyperttext=CypherText.Replace(' ', '+');
byte[] b = Convert.FromBase64String(newcyperttext);
TripleDES des = CreateDES("DreamMLMKey");
ICryptoTransform ct = des.CreateDecryptor();
byte[] output = ct.TransformFinalBlock(b, 0, b.Length);
return Encoding.Unicode.GetString(output);
}
#region encryption & Decription
public string Encrypt(string input, string key)
{
byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public string Decrypt(string input, string key)
{
byte[] inputArray = Convert.FromBase64String(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
public string encrypt(string encryptString)
{
string EncryptionKey = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
});
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
encryptString = Convert.ToBase64String(ms.ToArray());
}
}
return encryptString;
}
public string Decrypt(string cipherText)
{
string EncryptionKey = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
});
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
#endregion
}
Copied in my answer here from a similar question: Simple two-way encryption for C#.
Based on multiple answers and comments.
Random initialization vector prepended to crypto text (#jbtule)
Use TransformFinalBlock() instead of MemoryStream (#RenniePet)
No pre-filled keys to avoid anyone copy & pasting a disaster
Proper dispose and using patterns
Code:
/// <summary>
/// Simple encryption/decryption using a random initialization vector
/// and prepending it to the crypto text.
/// </summary>
/// <remarks>Based on multiple answers in https://stackoverflow.com/questions/165808/simple-two-way-encryption-for-c-sharp </remarks>
public class SimpleAes : IDisposable
{
/// <summary>
/// Initialization vector length in bytes.
/// </summary>
private const int IvBytes = 16;
/// <summary>
/// Must be exactly 16, 24 or 32 characters long.
/// </summary>
private static readonly byte[] Key = Convert.FromBase64String("FILL ME WITH 16, 24 OR 32 CHARS");
private readonly UTF8Encoding _encoder;
private readonly ICryptoTransform _encryptor;
private readonly RijndaelManaged _rijndael;
public SimpleAes()
{
_rijndael = new RijndaelManaged {Key = Key};
_rijndael.GenerateIV();
_encryptor = _rijndael.CreateEncryptor();
_encoder = new UTF8Encoding();
}
public string Decrypt(string encrypted)
{
return _encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));
}
public void Dispose()
{
_rijndael.Dispose();
_encryptor.Dispose();
}
public string Encrypt(string unencrypted)
{
return Convert.ToBase64String(Encrypt(_encoder.GetBytes(unencrypted)));
}
private byte[] Decrypt(byte[] buffer)
{
// IV is prepended to cryptotext
byte[] iv = buffer.Take(IvBytes).ToArray();
using (ICryptoTransform decryptor = _rijndael.CreateDecryptor(_rijndael.Key, iv))
{
return decryptor.TransformFinalBlock(buffer, IvBytes, buffer.Length - IvBytes);
}
}
private byte[] Encrypt(byte[] buffer)
{
// Prepend cryptotext with IV
byte[] inputBuffer = _rijndael.IV.Concat(buffer).ToArray();
return _encryptor.TransformFinalBlock(inputBuffer, IvBytes, buffer.Length);
}
}
Here is simple Snippet originally by ASP Snippets
using System.Text;
using System.Security.Cryptography;
using System.IO;
private string Encrypt(string clearText)
{
string EncryptionKey = "yourkey";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
private string Decrypt(string cipherText)
{
string EncryptionKey = "yourkey";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
AES Algorithm:
public static class CryptographyProvider
{
public static string EncryptString(string plainText, out string Key)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
using (Aes _aesAlg = Aes.Create())
{
Key = Convert.ToBase64String(_aesAlg.Key);
ICryptoTransform _encryptor = _aesAlg.CreateEncryptor(_aesAlg.Key, _aesAlg.IV);
using (MemoryStream _memoryStream = new MemoryStream())
{
_memoryStream.Write(_aesAlg.IV, 0, 16);
using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, _encryptor, CryptoStreamMode.Write))
{
using (StreamWriter _streamWriter = new StreamWriter(_cryptoStream))
{
_streamWriter.Write(plainText);
}
return Convert.ToBase64String(_memoryStream.ToArray());
}
}
}
}
public static string DecryptString(string cipherText, string Key)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(Key))
throw new ArgumentNullException("Key");
string plaintext = null;
byte[] _initialVector = new byte[16];
byte[] _Key = Convert.FromBase64String(Key);
byte[] _cipherTextBytesArray = Convert.FromBase64String(cipherText);
byte[] _originalString = new byte[_cipherTextBytesArray.Length - 16];
Array.Copy(_cipherTextBytesArray, 0, _initialVector, 0, _initialVector.Length);
Array.Copy(_cipherTextBytesArray, 16, _originalString, 0, _cipherTextBytesArray.Length - 16);
using (Aes _aesAlg = Aes.Create())
{
_aesAlg.Key = _Key;
_aesAlg.IV = _initialVector;
ICryptoTransform decryptor = _aesAlg.CreateDecryptor(_aesAlg.Key, _aesAlg.IV);
using (MemoryStream _memoryStream = new MemoryStream(_originalString))
{
using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader _streamReader = new StreamReader(_cryptoStream))
{
plaintext = _streamReader.ReadToEnd();
}
}
}
}
return plaintext;
}
}
Here is the sample how AES-GCM encryption/decryption can be done using Bouncy castle package.
I've found that sample when googled for possibility to decrypt data from GOlang crypto/aes api:
const (
gcmBlockSize = 16 // this is key size
gcmTagSize = 16 // this is mac
gcmStandardNonceSize = 12 // this is nonce
)
func encrypt(data []byte, passphrase string) []byte {
block, _ := aes.NewCipher([]byte(createHash(passphrase)))
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext
}
.Net sample works like a charm with key (256 bit), mac (128bit) and nonce (96 bit).
I have an open source project called X509Crypto that leverages certificates to encrypt and decrypt strings. It's very easy to use. Here is an example for how to use it:
1. Use the X509Crypto Commandline Interface (CLI) to generate a new encryption certificate and key pair
>x509crypto.exe
X509Crypto> makecert -context user -keysize medium -alias myvault
Certificate with thumbprint B31FE7E7AE5229F8186782742CF579197FA859FD was added to X509Alias "myvault" in the user X509Context
X509Crypto>
2. Use the Encrypt CLI command to add a secret to your new X509Alias
X509Crypto> encrypt -text -alias myvault -context user -secret apikey -in "80EAF03248965AC2B78090"
Secret apikey has been added to X509Alias myvault in the user X509Context
X509Crypto>
3. Reference the secret in your program
Once you have an X509Alias established with your secret(s) added, it is trivial to retreive them in your program with the Org.X509Crypto nuget package installed:
using Org.X509Crypto;
namespace SampleApp
{
class Program
{
static void Main(string[] args)
{
var Alias = new X509Alias(#"myvault", X509Context.UserReadOnly);
var apiKey = Alias.RecoverSecret(#"apikey");
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions; // This is for password validation
using System.Security.Cryptography;
using System.Configuration; // This is where the hash functions reside
namespace BullyTracker.Common
{
public class HashEncryption
{
//public string GenerateHashvalue(string thisPassword)
//{
// MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
// byte[] tmpSource;
// byte[] tmpHash;
// tmpSource = ASCIIEncoding.ASCII.GetBytes(thisPassword); // Turn password into byte array
// tmpHash = md5.ComputeHash(tmpSource);
// StringBuilder sOutput = new StringBuilder(tmpHash.Length);
// for (int i = 0; i < tmpHash.Length; i++)
// {
// sOutput.Append(tmpHash[i].ToString("X2")); // X2 formats to hexadecimal
// }
// return sOutput.ToString();
//}
//public Boolean VerifyHashPassword(string thisPassword, string thisHash)
//{
// Boolean IsValid = false;
// string tmpHash = GenerateHashvalue(thisPassword); // Call the routine on user input
// if (tmpHash == thisHash) IsValid = true; // Compare to previously generated hash
// return IsValid;
//}
public string GenerateHashvalue(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
// Get the key from config file
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
//System.Windows.Forms.MessageBox.Show(key);
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
/// <summary>
/// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
/// </summary>
/// <param name="cipherString">encrypted string</param>
/// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
/// <returns></returns>
public string Decrypt(string cipherString, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
//Get your key from config file to open the lock!
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
}
}
for simplicity i made for myself this function that i use for non crypto purposes : replace "yourpassphrase" with your password ...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace My
{
public class strCrypto
{
// This constant string is used as a "salt" value for the PasswordDeriveBytes function calls.
// This size of the IV (in bytes) must = (keysize / 8). Default keysize is 256, so the IV must be
// 32 bytes long. Using a 16 character string here gives us 32 bytes when converted to a byte array.
private const string initVector = "r5dm5fgm24mfhfku";
private const string passPhrase = "yourpassphrase"; // email password encryption password
// This constant is used to determine the keysize of the encryption algorithm.
private const int keysize = 256;
public static string encryptString(string plainText)
{
//if the plaintext is empty or null string just return an empty string
if (plainText == "" || plainText == null )
{
return "";
}
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
public static string decryptString(string cipherText)
{
//if the ciphertext is empty or null string just return an empty string
if (cipherText == "" || cipherText == null )
{
return "";
}
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
I want to give you my contribute, with my code for AES Rfc2898DeriveBytes (here the documentation) algorhytm, written in C# (.NET framework 4) and fully working also for limited platforms, as .NET Compact Framework for Windows Phone 7.0+ (not all platforms support every criptographic method of the .NET framework!).
I hope this can help anyone!
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static class Crypto
{
private static readonly byte[] IVa = new byte[] { 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11, 0x11, 0x12, 0x13, 0x14, 0x0e, 0x16, 0x17 };
public static string Encrypt(this string text, string salt)
{
try
{
using (Aes aes = new AesManaged())
{
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));
aes.Key = deriveBytes.GetBytes(128 / 8);
aes.IV = aes.Key;
using (MemoryStream encryptionStream = new MemoryStream())
{
using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] cleanText = Encoding.UTF8.GetBytes(text);
encrypt.Write(cleanText, 0, cleanText.Length);
encrypt.FlushFinalBlock();
}
byte[] encryptedData = encryptionStream.ToArray();
string encryptedText = Convert.ToBase64String(encryptedData);
return encryptedText;
}
}
}
catch
{
return String.Empty;
}
}
public static string Decrypt(this string text, string salt)
{
try
{
using (Aes aes = new AesManaged())
{
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));
aes.Key = deriveBytes.GetBytes(128 / 8);
aes.IV = aes.Key;
using (MemoryStream decryptionStream = new MemoryStream())
{
using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
byte[] encryptedData = Convert.FromBase64String(text);
decrypt.Write(encryptedData, 0, encryptedData.Length);
decrypt.Flush();
}
byte[] decryptedData = decryptionStream.ToArray();
string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
return decryptedText;
}
}
}
catch
{
return String.Empty;
}
}
}
}
You have to use the namespace using System.Security.Cryptography; and useHashing is a bool type either true or false. String variable "key" should be same for Encryption and for Decryption
//Encryption
public string EncryptText(string toEncrypt, bool useHashing)
{
try
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
string key = "String Key Value"; //Based on this key stirng is encrypting
//System.Windows.Forms.MessageBox.Show(key);
//If hashing use get hashcode regards to your key
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//Always release the resources and flush data
//of the Cryptographic service provide. Best Practice
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes. We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
//transform the specified region of bytes array to resultArray
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
catch (Exception e)
{
throw e;
}
}
//Decryption
public string DecryptText(string cipherString, bool useHashing)
{
try
{
byte[] keyArray;
//get the byte code of the string
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
string key = "String Key Value"; //Based on this key string is decrypted
if (useHashing)
{
//if hashing was used get the hash code with regards to your key
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//release any resource held by the MD5CryptoServiceProvider
hashmd5.Clear();
}
else
{
//if hashing was not implemented get the byte code of the key
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock
(toEncryptArray, 0, toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//return the Clear decrypted TEXT
return UTF8Encoding.UTF8.GetString(resultArray);
}
catch (Exception ex)
{
throw ex;
}
}
A good algorithm to securely hash data is BCrypt:
Besides incorporating a salt to protect against rainbow table attacks,
bcrypt is an adaptive function: over time, the iteration count can be
increased to make it slower, so it remains resistant to brute-force
search attacks even with increasing computation power.
There's a nice .NET implementation of BCrypt that is available also as a NuGet package.
using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;
namespace Encription
{
class CryptorEngine
{
public static string Encrypt(string ToEncrypt, bool useHasing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt);
//System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
string Key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));
hashmd5.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(Key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tDes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string cypherString, bool useHasing)
{
byte[] keyArray;
byte[] toDecryptArray = Convert.FromBase64String(cypherString);
//byte[] toEncryptArray = Convert.FromBase64String(cypherString);
//System.Configuration.AppSettingsReader settingReader = new AppSettingsReader();
string key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();
keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateDecryptor();
try
{
byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
tDes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length);
}
catch (Exception ex)
{
throw ex;
}
}
}
}

Categories

Resources