C#三层架构(获取中文拼音和给密码加密)

  在学习三层架构时,我们在需要获取中文字所获取的拼音,需要引进一个ChnCharInfo.dll的程序文件,并且引用命名空间

using Microsoft.International.Converters.PinYinConverter;

接下来是如何实现拼音的获取:

 1 public static string GetPinyins(string name)
 2         {
 3             //进行拼接字符串
 4             StringBuilder sb = new StringBuilder();
 5             //由于ChineseChar中必须为char类型,所以我们进行字符串遍历成char类型
 6             foreach (char item in name)
 7             {
 8                 //判断得到的字符是否为合法的中文字符
 9                 if (ChineseChar.IsValidChar(item))
10                 {
11                     //如果是合法的,那么执行下面的语句
12                     ChineseChar c = new ChineseChar(item);
13                     //根据传入的字符得到拼音
14                     ReadOnlyCollection<string> ps = c.Pinyins;
15                     //拼接字符串,这里说明一下:由于拼音是有声韵的,在这里得到的拼音也是包含音调,即ps的最后一个字符
16                     //所以我们要截取字符串,保留前面的
17                     sb.Append(ps[0].Substring(0, ps[0].Length - 1));
18                 }
19                 else
20                 {
21                     //如果为不合法的,不用获取,直接拼接
22                     sb.Append(item);
23                 }
24             }
25             //返回得到的拼接字符串
26             return sb.ToString();
27         } 

那怎么获取对密码加密呢?

首先也要引用:

using System.Security.Cryptography;

实现:

 1 public static string GetMD5(string pwd)
 2         {
 3             //这里我们使用的Winform自带的MD5加密
 4             //这里的MD5为私有的不可访问的,不过提供了一个可以访问的公共的方法进行创建
 5             MD5 md5 = MD5.Create();
 6             //准备拼接字符串
 7             StringBuilder sb = new StringBuilder();
 8             //通过用户传入的密码得到byte数组
 9             byte[] bytes = Encoding.Default.GetBytes(pwd);
10             //将得到的byte数组进行计算Hash码
11             byte[] newBytes = md5.ComputeHash(bytes);
12             //遍历每一个Hash码进行16进制的转换
13             foreach (byte item in newBytes)
14             {
15                 //将Hash进行16进制格式的转换
16                 sb.Append(item.ToString("X2"));
17             }
18             //返回得到的拼接字符串,即得到32位的加密密文
19             return sb.ToString();
20         } 

 

posted @ 2014-11-12 21:33  my_paradise  阅读(315)  评论(0编辑  收藏  举报