By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,561 Members | 3,221 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,561 IT Pros & Developers. It's quick & easy.

encrypt/decrypt

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

Hrcko
Nov 17 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
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.1415926535897932384626 43383279");
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(Con vert.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();
}

"Hrvoje Voda" wrote:
Does anyone knows a good example of how to encrypt/decrypt a string?

Hrcko

Nov 17 '05 #2

P: n/a
"Hrvoje Voda" <hr*********@luatech.com> wrote in message
news:d3**********@ss405.t-com.hr...
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);
Nov 17 '05 #3

P: n/a
Mark Rae <ma**@mark-N-O-S-P-A-M-rae.co.uk> wrote:
"Hrvoje Voda" <hr*********@luatech.com> wrote in message
news:d3**********@ss405.t-com.hr...
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);


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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #4

P: n/a
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
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(str Key));
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().T ransformFinalBlock(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.CreateDecrypto r().TransformFinalBlock(mabtyBuffer,
0, mabtyBuffer.Length));
}
catch (Exception)
{
throw;
}
finally
{
Deconstruct();
}
}
}
}
Nov 17 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.