Hello Hassan,
Is this what you are looking for?
- You may exchange alg and the associated aux functions to match your needs.
- If you have a byte array instead of a C# string, you may leave away the Unicode conversions to byte array.
- If you do not need a printable representation, leave the base64 parts away.
See also:
Simple encrypting and decrypting data in C#.
Cheers
Andi
public class StringEncryption
{
private static readonly byte[] salt = new byte[] { ... };
public static string Encrypt(string plainText, params byte[] password)
{
using (var ms = new MemoryStream())
{
using (var alg = Rijndael.Create())
using (var pwd = new Rfc2898DeriveBytes(password, salt, 1000))
using (var cs = new CryptoStream(ms, GetEncryptor(alg, pwd),
CryptoStreamMode.Write))
{
byte[] plainBytes = Encoding.Unicode.GetBytes(plainText);
cs.Write(plainBytes, 0, plainBytes.Length);
}
byte[] encodedBytes = ms.ToArray();
string base64string = Convert.ToBase64String(encodedBytes,
base64FormattingOptions.None);
return base64string;
}
}
public static string Decrypt(string encryptedText, params byte[] password)
{
using (var ms = new MemoryStream())
{
using (var alg = Rijndael.Create())
using (var pwd = new Rfc2898DeriveBytes(password, salt, 1000))
using (var cs = new CryptoStream(ms, GetDecryptor(alg, pwd),
CryptoStreamMode.Write))
{
byte[] decodedBytes = Convert.FromBase64String(encryptedText);
cs.Write(decodedBytes, 0, decodedBytes.Length);
}
byte[] decryptedBytes = ms.ToArray();
string plainText = Encoding.Unicode.GetString(decryptedBytes);
return plainText;
}
}
private static ICryptoTransform GetEncryptor(SymmetricAlgorithm algorithm,
DeriveBytes pwd)
{
return algorithm.CreateEncryptor(pwd.GetBytes(32), pwd.GetBytes(16));
}
private static ICryptoTransform GetDecryptor(SymmetricAlgorithm algorithm,
DeriveBytes pwd)
{
return algorithm.CreateDecryptor(pwd.GetBytes(32), pwd.GetBytes(16));
}
}