C# 加密-散列算法

string plaintext = "明文";
byte[] srcBuffer = System.Text.Encoding.UTF8.GetBytes(plaintext);

HashAlgorithm hash = HashAlgorithm.Create("SHA1"); //将参数换成“MD5”,则执行 MD5 加密。不区分大小写。
byte[] destBuffer = hash.ComputeHash(srcBuffer);

string hashedText = BitConverter.ToString(destBuffer).Replace("-", "");

用的是 HashAlgorithm 这个类,其名称空间是 System.Security.Cryptography。只用了它的两个方法:CreateComputeHash,ComputeHash 返回的是 byte[],为了显示这里转换成字符串,转换之后,它和前一节讲的 SHA1 结果是一样的。

也可以用 SHA1ManagedSHA1CryptoServiceProvider,但是我们推荐用本文的方法,因为它不涉及类名,要更改算法,只需要更改 Create 的字符串参数即可

posted on 2009-11-30 11:09  冬日阳光  阅读(315)  评论(0编辑  收藏  举报

导航