Friday, December 12, 2008

Encrypting a String in C# (.Net)

There are many options to encode a string in C# (.Net).

Here is mine using TripleDES encryption.

using System;
using System.IO;
using System.Security.Cryptography;

namespace StringEncrypter
{
internal class Program
{
private static ICryptoTransform _decryptor;
private static ICryptoTransform _encryptor;

private static void Main()
{
var TDES = TripleDES.Create();

TDES.GenerateIV();
TDES.GenerateKey();
_encryptor = TDES.CreateEncryptor();
_decryptor = TDES.CreateDecryptor();

byte[] encrypted = Encrypt("secret string");
string decrypted = Decrypt(encrypted);
Console.WriteLine(decrypted);
}

private static byte[] Encrypt(string plain)
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream =
new CryptoStream(memoryStream, _encryptor, CryptoStreamMode.Write))
using (StreamWriter writer = new StreamWriter(cryptoStream))
{
writer.Write(plain);
}
return memoryStream.ToArray();
}


}


private static string Decrypt(byte[] encrypted)
{

using (MemoryStream memoryStream = new MemoryStream(encrypted))
using (CryptoStream cryptoStream =
new CryptoStream(memoryStream, _decryptor, CryptoStreamMode.Read))
using (StreamReader reader = new StreamReader(cryptoStream))
{
return reader.ReadToEnd();
}
}
}
}
Post a Comment