





































































































顺便把C++的也备份下,明天下了VC++6,温习下MFC。
1
//
This sample demonstrates using a key based on the cryptographic service provider (CSP) version
2
//
of the Data Encryption Standard (DES)algorithm to encrypt a string to a byte array, and then
3
//
to decrypt the byte array back to a string.
4
using
namespace
System;
5
using
namespace
System::IO;
6
using
namespace
System::Text;
7
using
namespace
System::Security::Cryptography;
8
9
//
Encrypt the string.
10
array
<
Byte
>^
Encrypt( String
^
PlainText, SymmetricAlgorithm
^
key )
11
{
12
13
// Create a memory stream.
14
MemoryStream^ ms = gcnew MemoryStream;
15
16
// Create a CryptoStream using the memory stream and the
17
// CSP DES key.
18
CryptoStream^ encStream = gcnew CryptoStream( ms,key->CreateEncryptor(),CryptoStreamMode::Write );
19
20
// Create a StreamWriter to write a string
21
// to the stream.
22
StreamWriter^ sw = gcnew StreamWriter( encStream );
23
24
// Write the plaintext to the stream.
25
sw->WriteLine( PlainText );
26
27
// Close the StreamWriter and CryptoStream.
28
sw->Close();
29
encStream->Close();
30
31
// Get an array of bytes that represents
32
// the memory stream.
33
array<Byte>^buffer = ms->ToArray();
34
35
// Close the memory stream.
36
ms->Close();
37
38
// Return the encrypted byte array.
39
return buffer;
40
}
41
42
43
//
Decrypt the byte array.
44
String
^
Decrypt( array
<
Byte
>^
CypherText, SymmetricAlgorithm
^
key )
45
{
46
47
// Create a memory stream to the passed buffer.
48
MemoryStream^ ms = gcnew MemoryStream( CypherText );
49
50
// Create a CryptoStream using the memory stream and the
51
// CSP DES key.
52
CryptoStream^ encStream = gcnew CryptoStream( ms,key->CreateDecryptor(),CryptoStreamMode::Read );
53
54
// Create a StreamReader for reading the stream.
55
StreamReader^ sr = gcnew StreamReader( encStream );
56
57
// Read the stream as a string.
58
String^ val = sr->ReadLine();
59
60
// Close the streams.
61
sr->Close();
62
encStream->Close();
63
ms->Close();
64
return val;
65
}
66
67
int
main()
68
{
69
70
// Create a new DES key.
71
DESCryptoServiceProvider^ key = gcnew DESCryptoServiceProvider;
72
73
// Encrypt a string to a byte array.
74
array<Byte>^buffer = Encrypt( "This is some plaintext!", key );
75
76
// Decrypt the byte array back to a string.
77
String^ plaintext = Decrypt( buffer, key );
78
79
// Display the plaintext value to the console.
80
Console::WriteLine( plaintext );
81
}
82
83

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
