static class EncryptClass
{
// http://www.codeproject.com/KB/cs/Cryptography.aspx
///
/// Encrypt a string using dual encryption method. Return a encrypted cipher Text
///
/// string to be encrypted
/// use hashing? send to for extra secirity
///
public static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
string key = Properties.Settings.Default.SecurityKey; //<-- crealo en tu configuracion
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
///
/// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
///
/// encrypted string
/// Did you use hashing to encrypt this data? pass true is yes
///
public static string Decrypt(string cipherString, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = {0};
try
{
/*
* La longitud de cadena enritptada con Hashing es de 24
* si es menor de 24 lanza una excepcion, asi que hay que pasar de ella
*/
toEncryptArray = Convert.FromBase64String(cipherString);
}
catch (Exception)
{
return null;
}
string key = Properties.Settings.Default.SecurityKey;
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
}
Creas un valor de configuracion llamado SecurityKey en tu proyecto y le asignas un valor aleatorio
Fuente: http://www.codeproject.com/KB/cs/Cryptography.aspx
Publicado en tttony.blogspot.com
Publicar un comentario
No hay comentarios.:
Publicar un comentario