加密解密常用函数

合集下载
相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

本帖最后由小平于2013-6-22 10:05 编辑

#region DES加密解密

///

/// DES加密

///

/// 待加密字串

/// 32位Key值

/// 加密后的字符串

public string DESEncrypt(string strSource)

{

return DESEncrypt(strSource, DESKey);

}

public string DESEncrypt(string strSource, byte[] key)

{

SymmetricAlgorithm sa = Rijndael.Create();

sa.Key = key;

sa.Mode = CipherMode.ECB;

sa.Padding = PaddingMode.Zeros;

MemoryStream ms = new MemoryStream();

CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(), CryptoStreamMode.Write);

byte[] byt = Encoding.Unicode.GetBytes(strSource);

cs.Write(byt, 0, byt.Length);

cs.FlushFinalBlock();

cs.Close();

return Convert.ToBase64String(ms.ToArray());

}

///

/// DES解密

///

/// 待解密的字串 /// 32位Key值

/// 解密后的字符串

public string DESDecrypt(string strSource)

{

return DESDecrypt(strSource, DESKey);

}

public string DESDecrypt(string strSource, byte[] key) {

SymmetricAlgorithm sa = Rijndael.Create();

sa.Key = key;

sa.Mode = CipherMode.ECB;

sa.Padding = PaddingMode.Zeros;

ICryptoTransform ct = sa.CreateDecryptor();

byte[] byt = Convert.FromBase64String(strSource);

MemoryStream ms = new MemoryStream(byt);

CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Read);

StreamReader sr = new StreamReader(cs, Encoding.Unicode);

return sr.ReadToEnd();

}

#endregion

#region 一个用hash实现的加密解密方法

///

/// 加密

///

///

///

public static string EncryptStrByHash(string src)

{

if (src.Length == 0)

{

return "";

}

byte[] HaKey = System.Text.Encoding.ASCII.GetBytes((src + "Test").ToCharArray());

byte[] HaData = new byte[20];

HMACSHA1 Hmac = new HMACSHA1(HaKey);

CryptoStream cs = new CryptoStream(Stream.Null, Hmac, CryptoStreamMode.Write);

try

{

cs.Write(HaData, 0, HaData.Length);

}

finally

{

cs.Close();

}

string HaResult = System.Convert.ToBase64String(Hmac.Hash).Substring(0, 16);

byte[] RiKey = System.Text.Encoding.ASCII.GetBytes(HaResult.ToCharArray());

byte[] RiDataBuf = System.Text.Encoding.ASCII.GetBytes(src.ToCharArray());

byte[] EncodedBytes = { };

MemoryStream ms = new MemoryStream();

RijndaelManaged rv = new RijndaelManaged();

cs = new CryptoStream(ms, rv.CreateEncryptor(RiKey, RiKey),

相关文档
最新文档