Monday, March 16, 2009

Cryptography

If you are looking to encrypt/decrypt data, this is what I was able to put together from some other sites I found.

I am using GUIDs for both the Key and the Salt for the encryption, which I am getting from Unique IDs from within the data itself.

1. Add this code. I added it to a namespace of Customer.Business.Util

/// <summary>
/// Encrypt or Decrypt a String
/// </summary>
/// <param name="CryptType">(E)ncrypt or (D)ecrpt</param>
/// <param name="TextToConvert">The Text to be encrypted or decrypted.</param>
/// <param name="Key">The Key for encryption.</param>
/// <param name="IV">The Salt for encryption.</param>
/// <returns>The Text converted.</returns>
public static string CryptString(char CryptType, string TextToConvert, byte[] Key, byte[] IV)
{
try
{
// Create a new instance of the RijndaelManaged
// class. This generates a new key and initialization
// vector (IV).
RijndaelManaged myRijndael = new RijndaelManaged();
// Change Key and Salt to user provided Key and Salt
myRijndael.Key = Key;
myRijndael.IV = IV;

if (CryptType.ToString() == "D")
{ // decrypt
return decryptString_AES(TextToConvert, myRijndael.Key, myRijndael.IV);
}
else
{ // encrypt
return encryptString_AES(TextToConvert, myRijndael.Key, myRijndael.IV);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return string.Empty;
}
}

private static string encryptString_AES(string plainText, byte[] Key, byte[] IV)
{
string encryptText = string.Empty;
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Salt");

// Declare the stream used to encrypt to an in memory
// array of bytes.
MemoryStream msEncrypt = null;

// Declare the RijndaelManaged object
// used to encrypt the data.
RijndaelManaged aesAlg = null;

try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = Key;
aesAlg.IV = IV;

// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(Key, IV);

// Create the streams used for encryption.
msEncrypt = new MemoryStream();
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
byte[] b = msEncrypt.ToArray();
encryptText = Convert.ToBase64String(b);
return encryptText;
}

private static string decryptString_AES(string cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0 || cipherText == string.Empty)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Salt");

//Convert to byte[]
byte[] cipherByte = Convert.FromBase64String(cipherText.Trim());

// 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
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = Key;
aesAlg.IV = IV;

// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(Key, IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherByte))
{
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;
}


2. Call the Method to Encrypt like this.

encryptedNumber = Customer.Business.Util.CryptString('E', Payment1.AccountNumber, OrderFormId.ToByteArray(), PaymentId.ToByteArray());


3. Call the same Method to Decrypt like this.

decryptedCode = Customer.Business.Util.CryptString('D', encryptedCode, OrderFormId.ToByteArray(), PaymentId.ToByteArray());

No comments:

Post a Comment