DESCryptoServiceProvider 类

DESCryptoServiceProvider 类

定义访问数据加密标准 (DES) 算法的加密服务提供程序 (CSP) 版本的包装对象。无法继承此类。

命名空间:System.Security.Cryptography
程序集:mscorlib(在 mscorlib.dll 中)

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

 
// This sample demonstrates using a key based on the cryptographic service provider (CSP) version
// of the Data Encryption Standard (DES)algorithm to encrypt a string to a byte array, and then
// to decrypt the byte array back to a string.

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

class CryptoMemoryStream
{
// Main method.
public static void Main()
{
// Create a new DES key.
DESCryptoServiceProvider key = new DESCryptoServiceProvider();

// Encrypt a string to a byte array.
byte[] buffer = Encrypt("This is some plaintext!", key);

// Decrypt the byte array back to a string.
string plaintext = Decrypt(buffer, key);

// Display the plaintext value to the console.
Console.WriteLine(plaintext);
}

// Encrypt the string.
public static byte[] Encrypt(string PlainText, SymmetricAlgorithm key)
{
// Create a memory stream.
MemoryStream ms = new MemoryStream();

// Create a CryptoStream using the 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 plaintext to the stream.
sw.WriteLine(PlainText);

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

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

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

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

// Decrypt the byte array.
public static string Decrypt(byte[] CypherText, SymmetricAlgorithm key)
{
// Create a memory stream to the passed buffer.
MemoryStream ms = new MemoryStream(CypherText);

// Create a CryptoStream using the 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);

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

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

return val;
}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值