本文实例讲述了C#实现简易的加密、解密字符串工具类。分享给大家供大家参考。具体如下:
这里的类CypherHelper是一个用于加密、解密字符串的工具类~~~,适合于方便地加密、解密长度较短的密码等字符串(C#里面已经有了库System.Security.Cryptography,对于比较长的字符串或流来说是一个更好的选择)
类CypherHelper代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
class CypherHelper { /// <summary> /// 加密字符串 /// </summary> /// <param name="word">被加密字符串</param> /// <param name="key">密钥</param> /// <returns>加密后字符串</returns> public static string Encrypt( string word, string key) { if (!System.Text.RegularExpressions.Regex.IsMatch(key, "^[a-zA-Z]*$" )) { throw new Exception( "key 必须由字母组成" ); } key = key.ToLower(); //逐个字符加密字符串 char [] s = word.ToCharArray(); for ( int i = 0; i < s.Length; i++) { char a = word[i]; char b = key[i % key.Length]; s[i] = EncryptChar(a, b); } return new string (s); } /// <summary> /// 加密单个字符 /// </summary> /// <param name="a">被加密字符</param> /// <param name="b">密钥</param> /// <returns>加密后字符</returns> private static char EncryptChar( char a, char b) { int c = a + b - 'a' ; if (a >= '0' && a <= '9' ) //字符0-9的转换 { while (c > '9' ) c -= 10; } else if (a >= 'a' && a <= 'z' ) //字符a-z的转换 { while (c > 'z' ) c -= 26; } else if (a >= 'A' && a <= 'Z' ) //字符A-Z的转换 { while (c > 'Z' ) c -= 26; } else return a; //不再上面的范围内,不转换直接返回 return ( char )c; //返回转换后的字符 } /// <summary> /// 解密字符串 /// </summary> /// <param name="word">被解密字符串</param> /// <param name="key">密钥</param> /// <returns>解密后字符串</returns> public static string Decrypt( string word, string key) { if (!System.Text.RegularExpressions.Regex.IsMatch(key, "^[a-zA-Z]*$" )) { throw new Exception( "key 必须由字母组成" ); } key = key.ToLower(); //逐个字符解密字符串 char [] s = word.ToCharArray(); for ( int i = 0; i < s.Length; i++) { char a = word[i]; char b = key[i % key.Length]; s[i] = DecryptChar(a, b); } return new string (s); } /// <summary> /// 解密单个字符 /// </summary> /// <param name="a">被解密字符</param> /// <param name="b">密钥</param> /// <returns>解密后字符</returns> private static char DecryptChar( char a, char b) { int c = a - b + 'a' ; if (a >= '0' && a <= '9' ) //字符0-9的转换 { while (c < '0' ) c += 10; } else if (a >= 'a' && a <= 'z' ) //字符a-z的转换 { while (c < 'a' ) c += 26; } else if (a >= 'A' && a <= 'Z' ) //字符A-Z的转换 { while (c < 'A' ) c += 26; } else return a; //不再上面的范围内,不转换直接返回 return ( char )c; //返回转换后的字符 } } |
Main函数调用示例
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Program { static void Main( string [] args) { //1.加密 string a = CypherHelper.Encrypt( "TsybiusLee1234" , "Galatea" ); Console.WriteLine( "加密:TsybiusLee1234 → " + a); //2.解密 string b = CypherHelper.Decrypt(a, "Galatea" ); Console.WriteLine( "解密:" + a + " → " + b); Console.ReadLine(); } } |
运行结果
希望本文所述对大家的C#程序设计有所帮助。