encrypt/decrypt

G

Guest

Hi,

You can use the System.Security.Cryptography, you have several ways to
encrypt, using public/private keys or using fixed keys.

The following example shows how to use Rijndael using fixed keys (this
encryption method is the strongest -256bits-)


Constructor:
/// <summary>
/// Main key (32 bytes)
/// </summary>
private byte[] m_key;
/// <summary>
/// Main initializer vector (16 bytes)
/// </summary>
private byte[] m_IV;
private ICryptoTransform m_Encryptor;

m_TextConverter = new ASCIIEncoding();
m_ObjRijndael = new RijndaelManaged();

// Sample keys
m_key = m_TextConverter.GetBytes("3.141592653589793238462643383279");
m_IV = m_TextConverter.GetBytes("FEDCBA9876543210");

m_Encryptor = m_ObjRijndael.CreateEncryptor(m_key, m_IV);

//////////////////////////////////////
Encrypt
//////////////////////////////////////
public string Encrypt(string text)
{
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, m_Encryptor,
CryptoStreamMode.Write);

toEncrypt = m_TextConverter.GetBytes(text);
msEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock()

return ConvertBytesToHexString(msEncrypt.ToArray());

/////////////////////////////////////////////////////
Decrypt
////////////////////////////////////////////////////
public string Decrypt (string text)
{
ICryptoTransform decryptor = m_ObjRijndael.CreateDecryptor(m_key, m_IV);

MemoryStream msDecrypt = new MemoryStream(ConvertHexStringToBytes(text));
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor,
CryptoStreamMode.Read);

byte[] fromEncrypt = new byte[msDecrypt.Length];
csDecrypt.Read(fromEncrypt, 0, (int)msDecrypt.Length);

return m_TextConverter.GetString(fromEncrypt).TrimEnd(Convert.ToChar('\0'));
}

//////////////////////////////////////////
String to Hex
/////////////////////////////////////////
private string ConvertBytesToHexString(byte[] data)
{
StringBuilder Results = new StringBuilder(data.Length/2);

foreach (byte part in data)
Results.Append(part.ToString("X2"));

return Results.ToString();
}
 
M

Mark Rae

Does anyone knows a good example of how to encrypt/decrypt a string?

See the code Salvador suggested. Create yourself a class (e.g.
CEncryption.cs) and just drop the code straight in. If you make the two
methods (Encrypt & Decrypt) static, you won't even need to instantiate the
class each time, e.g.

string strRegularText = "Hello world";
string strEncryptedText = CEncryption.Encrypt(strRegularText);
 
J

Jon Skeet [C# MVP]

Mark Rae said:
See the code Salvador suggested. Create yourself a class (e.g.
CEncryption.cs) and just drop the code straight in. If you make the two
methods (Encrypt & Decrypt) static, you won't even need to instantiate the
class each time, e.g.

string strRegularText = "Hello world";
string strEncryptedText = CEncryption.Encrypt(strRegularText);

Note, however, that you should avoid using ASCII as your encoding
(that's what Salvador's class does) as it means only unicode values
0-127 will be correctly handled.

I'd suggest using UTF-8.
 
M

Mark Rae

Note, however, that you should avoid using ASCII as your encoding
(that's what Salvador's class does) as it means only unicode values
0-127 will be correctly handled.

Yes indeed.
I'd suggest using UTF-8.

I couldn't agree more. If it helps anyone, this is my generic Encryption
class:


using System;
using System.Security.Cryptography;
using System.Text;

namespace shared
{
/// <summary>
/// Encrypts and decrypts strings using DES3 encryption and the .NET
Framework
/// </summary>
public sealed class CEncryption
{
static byte[] mabtyBuffer;
static TripleDESCryptoServiceProvider mobjDES;

/// <summary>
/// Create a secret key. The key is used to encrypt and decrypt strings.
/// Without the key, the encrypted string cannot be decrypted and is just
garbage.
/// You must use the same key to decrypt an encrypted string as the string
was originally encrypted with.
/// </summary>
private static void Construct()
{
string strKey = "";
MD5CryptoServiceProvider hashmd5;
byte[] abytKeyHash;

strKey += <well I'm hardly going to tell you my key...!>

/// <remarks>
/// Generate an MD5 hash from the key.
/// A hash is a one way encryption meaning once you generate
/// the hash, you can't derive the key back from it.
/// </remarks>
hashmd5 = new MD5CryptoServiceProvider();
abytKeyHash = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(strKey));
hashmd5 = null;

mobjDES = new TripleDESCryptoServiceProvider(); //implement DES3
encryption
mobjDES.Key = abytKeyHash; //the key is the secret key hash.

/// <remarks>
/// The mode is the block cipher mode which is basically the details of
how the encryption will work.
/// There are several kinds of ciphers available in DES3 and they all
have benefits and drawbacks.
/// Here the Electronic Codebook cipher is used which means that a given
bit of text is always encrypted
/// exactly the same when the same key is used.
/// </remarks>
mobjDES.Mode = CipherMode.ECB; //CBC, CFB
}

private static void Deconstruct()
{
if(mobjDES != null)
{
mobjDES = null;
}
}

/// <summary>
/// To encrypt an unencrypted string
/// </summary>
/// <param name="pstrText">Text to be encrypted</param>
/// <returns>Encrypted text</returns>
public static string Encrypt(string pstrText)
{
try
{
Construct();
//mabtyBuffer = ASCIIEncoding.ASCII.GetBytes(pstrText);
mabtyBuffer = UTF8Encoding.UTF8.GetBytes(pstrText);
return
Convert.ToBase64String(mobjDES.CreateEncryptor().TransformFinalBlock(mabtyBuffer,
0, mabtyBuffer.Length));
}
catch (Exception)
{
throw;
}
finally
{
Deconstruct();
}
}

/// <summary>
/// To decrypt an encrypted string
/// </summary>
/// <param name="pstrText">Text to be decrypted</param>
/// <returns>Decrypted text</returns>
public static string Decrypt(string pstrText)
{
try
{
Construct();
mabtyBuffer = Convert.FromBase64String(pstrText);
return
UTF8Encoding.UTF8.GetString(mobjDES.CreateDecryptor().TransformFinalBlock(mabtyBuffer,
0, mabtyBuffer.Length));
}
catch (Exception)
{
throw;
}
finally
{
Deconstruct();
}
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top