1
using System;
2
using System.IO;
3
using System.Security.Cryptography;
4
using System.Text;
5
6
namespace FaibClass.Encrypting
7
{
8
9
public class BaseEncrypt
10
{
11
//// <summary>
12
/// 加密
13
/// </summary>
14
/// <param name="s">需加密的字串</param>
15
/// <param name="k">密钥</param>
16
/// <returns></returns>
17
public static string EncryptString(string s,string k)
18
{
19
byte[] byKey=null;
20
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
21
try
22
{
23
if(k.Length>8)
24
byKey = System.Text.Encoding.UTF8.GetBytes(k.Substring(0,8));
25
else
26
byKey = System.Text.Encoding.UTF8.GetBytes((k+(new string('V',8-k.Length))));
27
28
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
29
byte[] inputByteArray = Encoding.UTF8.GetBytes(s);
30
MemoryStream ms = new MemoryStream();
31
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write) ;
32
cs.Write(inputByteArray, 0, inputByteArray.Length);
33
cs.FlushFinalBlock();
34
return Convert.ToBase64String(ms.ToArray());
35
}
36
catch(System.Exception error)
37
{
38
throw new Exception(error.Message);
39
}
40
}
41
42
//// <summary>
43
/// 解密
44
/// </summary>
45
/// <param name="s">需解密的字串</param>
46
/// <param name="k">密钥</param>
47
/// <returns></returns>
48
public static string DecryptString(string s,string k)
49
{
50
byte[] byKey = null;
51
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
52
byte[] inputByteArray = new Byte[s.Length];
53
try
54
{
55
if(k.Length>8)
56
byKey = System.Text.Encoding.UTF8.GetBytes(k.Substring(0,8));
57
else
58
byKey = System.Text.Encoding.UTF8.GetBytes((k+(new string('V',8-k.Length))));
59
60
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
61
inputByteArray = Convert.FromBase64String(s);
62
MemoryStream ms = new MemoryStream();
63
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
64
cs.Write(inputByteArray, 0, inputByteArray.Length);
65
cs.FlushFinalBlock();
66
System.Text.Encoding encoding = new System.Text.UTF8Encoding();
67
return encoding.GetString(ms.ToArray());
68
}
69
catch(System.Exception error)
70
{
71
throw new Exception(error.Message);
72
}
73
}
74
}
75
}

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
