这个字符串加密解密类是广大程序员必不可少的[静态类]
1
using System;
2
using System.Text;
3
using System.Security.Cryptography;
4
using System.IO;
5
6
7
8
//默认密钥向量
9
private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
10
/**//// <summary>
11
/// DES加密字符串
12
/// </summary>
13
/// <param name="encryptString">待加密的字符串</param>
14
/// <param name="encryptKey">加密密钥,要求为8位</param>
15
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
16
public static string EncryptDES(string encryptString, string encryptKey)
17
{
18
try
19
{
20
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
21
byte[] rgbIV = Keys;
22
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
23
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
24
MemoryStream mStream = new MemoryStream();
25
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
26
cStream.Write(inputByteArray, 0, inputByteArray.Length);
27
cStream.FlushFinalBlock();
28
return Convert.ToBase64String(mStream.ToArray());
29
}
30
catch
31
{
32
return encryptString;
33
}
34
}
35
36
/**//// <summary>
37
/// DES解密字符串
38
/// </summary>
39
/// <param name="decryptString">待解密的字符串</param>
40
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
41
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
42
public static string DecryptDES(string decryptString, string decryptKey)
43
{
44
try
45
{
46
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
47
byte[] rgbIV = Keys;
48
byte[] inputByteArray = Convert.FromBase64String(decryptString);
49
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
50
MemoryStream mStream = new MemoryStream();
51
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
52
cStream.Write(inputByteArray, 0, inputByteArray.Length);
53
cStream.FlushFinalBlock();
54
return Encoding.UTF8.GetString(mStream.ToArray());
55
}
56
catch
57
{
58
return decryptString;
59
}
60
}
61

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
