hi ,
i want to encrypt and decrypt a string.
to encrypt i have this:
string toencode;
byte[] text;
text = Encoding.Unicode.GetBytes(toencode);
SHA256Managed hash = new SHA256Managed();
texto = hash.ComputeHash(text);
Convert.ToBase64String(text);
to decrypt how can i do it?
thanks in advance
Loading
trkpowerPosted May 28, 2008, 7:55 AM
i tried doing with SHA1 but i'm getting a error saying "Specified key is not a valid size for this algorithm." do you know what could it be?
Thanks in advance.
Scott LyslePosted May 27, 2008, 1:21 PM
Encryption and decryption with a passkey:
using System;
using System.Security.Cryptography;
using System.Text;
#pragma warning disable 1591,1592,1573,1571,1570,1572
namespace Crypto
{
public static class Endecrypto
{
#region MD5 Hash
///
/// MD5 - Encrypt a plain text string using a key
///
///
///
/// A string containing the encrypted password
public static string EncryptMd5(string sOriginal, string sPassKey)
{
byte[] sPassKeyArray;
byte[] sOriginalArray = UTF8Encoding.UTF8.GetBytes(sOriginal);
MD5CryptoServiceProvider MD5Hash = new MD5CryptoServiceProvider();
sPassKeyArray = MD5Hash.ComputeHash(UTF8Encoding.UTF8.GetBytes(sPassKey));
MD5Hash.Clear();
TripleDESCryptoServiceProvider tripleDesCsp = new TripleDESCryptoServiceProvider();
tripleDesCsp.Key = sPassKeyArray;
tripleDesCsp.Mode = CipherMode.ECB;
tripleDesCsp.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDesCsp.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(sOriginalArray, 0, sOriginalArray.Length);
tripleDesCsp.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
///
/// MD5 - Decrypt an encrypted string using a key
///
///
///
/// A string containing the decrypted account number
public static string DecryptMd5(string sToOriginal, string sPassKey)
{
byte[] sPassKeyArray;
byte[] sOriginalArray = Convert.FromBase64String(sToOriginal);
MD5CryptoServiceProvider MD5Hash = new MD5CryptoServiceProvider();
sPassKeyArray = MD5Hash.ComputeHash(UTF8Encoding.UTF8.GetBytes(sPassKey));
MD5Hash.Clear();
TripleDESCryptoServiceProvider tripleDesCsp = new TripleDESCryptoServiceProvider();
tripleDesCsp.Key = sPassKeyArray;
tripleDesCsp.Mode = CipherMode.ECB;
tripleDesCsp.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDesCsp.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(sOriginalArray, 0, sOriginalArray.Length);
tripleDesCsp.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
#endregion
}
}