DESCryptoServiceProviderクラスの暗号化、復号化

9905 ワード

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace EncryptDemo
{
class Program
{
static void Main(string[] args)
{
// Create a new DES key.
DESCryptoServiceProvider key = new DESCryptoServiceProvider();

//get the input
string val = null;
val=Console.ReadLine().ToString();

// Encrypt a string to a byte array
byte[] encryptedByte = Encrypt(val, key);

//write out the encrypt result
if (encryptedByte != null)
for (int i = 0; i < encryptedByte.Length; i++)
{
Console.Write(encryptedByte[i]);
}

//Decrypt the encrypted byte array
val = Decrypt(encryptedByte, key);

Console.Write("
");

//write out the original data
Console.Write(val);

Console.ReadKey();
}

/// <summary>
/// a method to encrypt the string to a byte array
/// </summary>
/// <param name="strToEncrypt">the string need to encrypt</param>
/// <param name="key"> the CSP DES key</param>
/// <returns>a byte array</returns>
public static byte[] Encrypt(string strToEncrypt,SymmetricAlgorithm key)
{
//if the string is null, then return
if (strToEncrypt == null)
return null;

//create a memory stream
MemoryStream ms = new MemoryStream();

//create a cryptostream using memory stream and the CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);

//Create a StreamWriter to write a string to the stream.
StreamWriter sw = new StreamWriter(encStream);

// Write the strToEncrypt to the stream
sw.Write(strToEncrypt);

// Close the StreamWriter and CryptoStream.
sw.Close();
encStream.Close();

// Get an array of bytes that represents
// the memory stream.
byte[] result = ms.ToArray();

// Close the memory stream.
ms.Close();

// Return the encrypted byte array.
return result;
}

/// <summary>
/// a method to decrypt a encrypted byte to its original string
/// </summary>
/// <param name="byteToDecrypt">encrypted data, it must be a byte array</param>
/// <param name="key">the CSP DES key</param>
/// <returns>original string</returns>
public static string Decrypt(byte[] byteToDecrypt, SymmetricAlgorithm key)
{
//create a memory stream, as it will in read mode, so it must be new with the byteToDecrypt
MemoryStream ms = new MemoryStream(byteToDecrypt);

//create a cryptostream using memory stream and the CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);

// Create a StreamReader for reading the stream.
StreamReader sr = new StreamReader(encStream);

string result = "";

// Read the stream as a string.
result = sr.ReadLine();

// Close the streams.
sr.Close();

encStream.Close();

ms.Close();

return result;


}
}
}

注:MSDN参照