[引]VS2005帮助文档 : 加密 概述

本文介绍了加密的基本概念,包括加密的目的、常见的加密方案及其在.NET Framework中的实现。详细探讨了私钥加密、公钥加密、数字签名和哈希值等核心加密技术,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

本文主要包含以下内容:
01.  加密的目的
02.  大概的一些加密方案
03.  私钥加密
04.  .NET Framework 提供的实现私钥加密算法的类
05.  公钥加密
06.  .NET Framework 提供的实现公钥加密算法的类
07.  数字签名
08.  .NET Framework 提供以下实现数字签名算法的类
09.  哈希值
10.  .NET Framework 提供以下实现数字签名算法的类
11.  随机数生成
12.  .NET Framework 中的类使用随机数生成器生成加密密钥。
=============================

加密可以帮助保护数据不被查看和修改,
并且可以帮助在本不安全的信道上提供安全的通信方式。
例如,可以使用加密算法对数据进行加密,在加密状态下传输数据,
然后由预定的接收方对数据进行解密。
如果第三方截获了加密的数据,解密数据是很困难的。

在一个使用加密的典型场合中,双方(小红和小明)在不安全的信道上通信。
小红和小明想要确保任何可能正在侦听的人无法理解他们之间的通信。
而且,由于小红和小明相距遥远,
因此小红必须确保她从小明处收到的信息没有在传输期间被任何人修改。
此外,她必须确定信息确实是发自小明而不是有人模仿小明发出的。

1. 加密用于达到以下目的:
---------------------
保密性     :帮助保护用户的标识或数据不被读取。
数据完整性 :帮助保护数据不更改。
身份验证   :确保数据发自特定的一方。

为了达到这些目的,您可以使用算法和惯例的组合(称作加密基元)来创建加密方案。
2. 下表列出了加密基元及它们的用法。
--------------------------------
加密基元                     使用 
私钥加密(对称加密)         对数据执行转换,使第三方无法读取该数据。
                             此类型的加密使用单个共享的机密密钥来加密和解密数据。
 
公钥加密(不对称加密)       对数据执行转换,使第三方无法读取该数据。
                             此类加密使用公钥/私钥对来加密和解密数据。
 
加密签名                     通过创建对特定方唯一的数字签名
                                 来帮助验证数据是否发自特定方。
                             此过程还使用哈希函数。
 
加密哈希                     将数据从任意长度映射为定长字节序列。
                             哈希在统计上是唯一的;
                             不同的双字节序列不会哈希为同一个值。
 

3.私钥加密
---------
私钥加密算法使用单个私钥来加密和解密数据。
由于具有密钥的任意一方都可以使用该密钥解密数据,
因此必须保护密钥不被未经授权的代理得到。

私钥加密又称为对称加密,因为同一密钥既用于加密又用于解密。
私钥加密算法非常快(与公钥算法相比),特别适用于对较大的数据流执行加密转换。

通常,私钥算法(称为块密码)用于一次加密一个数据块。
块密码(如 RC2、DES、TripleDES 和 Rijndael)通过加密
将 n 字节的输入块转换为加密字节的输出块。

如果要加密或解密字节序列,必须逐块进行。

由于 n 很小(对于 RC2、DES 和 TripleDES,n = 8 字节;
n = 16 [默认值];n = 24;对于 Rijndael,n = 32),
因此必须对大于 n 的数据值一次加密一个块。

基类库中提供的块密码类使用称作密码块链 (CBC) 的链模式,
它使用一个密钥和一个初始化向量 (IV) 对数据执行加密转换。
对于给定的私钥 k,一个不使用初始化向量的简单块密码
将把相同的明文输入块加密为同样的密文输出块。
如果在明文流中有重复的块,那么在密文流中将存在重复的块。
如果未经授权的用户知道有关明文块的结构的任何信息,
就可以使用这些信息解密已知的密文块并有可能发现您的密钥。

若要克服这个问题,可将上一个块中的信息混合到加密下一个块的过程中。
这样,两个相同的明文块的输出就会不同。
由于该技术使用上一个块加密下一个块,
因此使用了一个 IV 来加密数据的第一个块。
使用该系统,
未经授权的用户有可能知道的公共消息标头将无法用于对密钥进行反向工程。

可以危及用此类型密码加密的数据的一个方法是,
对每个可能的密钥执行穷举搜索。
根据用于执行加密的密钥大小,
即使使用最快的计算机执行这种搜索,也极其耗时,
因此难以实施。使用较大的密钥大小将使解密更加困难。

虽然从理论上说加密不会使对手无法检索加密的数据,
但这确实极大增加了这样做的成本。
如果执行彻底搜索来检索只在几天内有意义的数据需要花费三个月的时间,
那么穷举搜索的方法是不实用的。

私钥加密的缺点是它假定双方已就密钥和 IV 达成协议,
并且互相传达了密钥和 IV 的值。
并且,密钥必须对未经授权的用户保密。
由于存在这些问题,
私钥加密通常与公钥加密一起使用,来秘密地传达密钥和 IV 的值。

假设小红和小明是要在不安全的信道上进行通信的双方,
他们可能按以下方式使用私钥加密。
小红和小明都同意使用一种具有特定密钥和 IV 的特定算法(如 Rijndael)。
小红撰写一条消息并创建要在其上发送该消息的网络流。
接下来,她使用该密钥和 IV 加密该文本,
并通过 Internet 发送该文本。
她没有将密钥和 IV 发送给小明。
小明收到该加密文本并使用预先商定的密钥和 IV 对它进行解密。
如果传输的内容被人截获,截获者将无法恢复原始消息,
因为截获者并不知道密钥或 IV。
在这个方案中,密钥必须保密,但 IV 不需要保密。

在一个实际方案中,
将由小红或小明生成私钥并使用公钥(不对称)加密将私钥(对称)传递给对方。

4.  .NET Framework 提供以下实现私钥加密算法的类:
--------------------------------------------
DESCryptoServiceProvider

RC2CryptoServiceProvider

RijndaelManaged

TripleDESCryptoServiceProvider

5.公钥加密
----------
公钥加密使用一个必须对未经授权的用户保密的私钥和一个可以对任何人公开的公钥。
公钥和私钥都在数学上相关联;
用公钥加密的数据只能用私钥解密,而用私钥签名的数据只能用公钥验证。
公钥可以提供给任何人;
公钥用于对要发送到私钥持有者的数据进行加密。
两个密钥对于通信会话都是唯一的。

公钥加密算法也称为不对称算法,
原因是需要用一个密钥加密数据而需要用另一个密钥来解密数据。

公钥加密算法使用固定的缓冲区大小,而私钥加密算法使用长度可变的缓冲区。
公钥算法无法像私钥算法那样将数据链接起来成为流,原因是它只可以加密少量数据。
因此,不对称操作不使用与对称操作相同的流模型。

双方(小红和小明)可以按照下列方式使用公钥加密。
首先,小红生成一个公钥/私钥对。
如果小明想要给小红发送一条加密的消息,他将向她索要她的公钥。
小红通过不安全的网络将她的公钥发送给小明,小明接着使用该密钥加密消息。
(如果小明在不安全的信道如公共网络上收到小红的密钥,
则小明必须同小红验证他具有她的公钥的正确副本。)
小明将加密的消息发送给小红,而小红使用她的私钥解密该消息。

但是,在传输小红的公钥期间,未经授权的代理可能截获该密钥。
而且,同一代理可能截获来自小明的加密消息。
但是,该代理无法用公钥解密该消息。
该消息只能用小红的私钥解密,而该私钥没有被传输。
小红不使用她的私钥加密给小明的答复消息,
原因是任何具有公钥的人都可以解密该消息。
如果小红想要将消息发送回小明,她将向小明索要他的公钥并使用该公钥加密她的消息。
然后,小明使用与他相关联的私钥来解密该消息。

在一个实际方案中,
小红和小明使用公钥(不对称)加密来传输私(对称)钥,
而对他们的会话的其余部分使用私钥加密。

公钥加密具有更大的密钥空间(或密钥的可能值范围),
因此不大容易受到对每个可能密钥都进行尝试的穷举攻击。
由于不必保护公钥,因此它易于分发。
公钥算法可用于创建数字签名以验证数据发送方的身份。
但是,公钥算法非常慢(与私钥算法相比),不适合用来加密大量数据。
公钥算法仅对传输很少量的数据有用。
公钥加密通常用于加密一个私钥算法将要使用的密钥和 IV。
传输密钥和 IV 后,会话的其余部分将使用私钥加密。

6.  .NET Framework 提供以下实现公钥加密算法的类:
----------------------------------------
DSACryptoServiceProvider

RSACryptoServiceProvider

7.数字签名
----------
公钥算法还可用于构成数字签名。
数字签名验证发送方的身份(如果您信任发送方的公钥)并帮助保护数据的完整性。
使用由小红生成的公钥,
小红的数据的接收者可以通过将数字签名与小红的数据和小红的公钥进行比较
来验证是否是小红发送了该数据。

为了使用公钥加密对消息进行数字签名,
小红首先将哈希算法应用于该消息以创建消息摘要。
该消息摘要是数据的紧凑且唯一的表示形式。
然后,小红用她的私钥加密该消息摘要以创建她的个人签名。
在收到消息和签名时,小明使用小红的公钥解密签名以恢复消息摘要,
并使用与小红所使用的相同的哈希算法来散列消息。
如果小明计算的消息摘要与从小红那里收到的消息摘要完全一致,
小明就可以确定该消息来自私钥的持有人,
并且数据未被修改过。
如果小明相信小红是私钥的持有人,则他知道该消息来自小红。

请注意,由于发送方的公钥为大家所周知,
并且它通常包含在数字签名格式中,因此任何人都可以验证签名。
此方法不保守消息的机密;
若要使消息保密,还必须对消息进行加密。

8.  .NET Framework 提供以下实现数字签名算法的类:
-------------------------
DSACryptoServiceProvider

RSACryptoServiceProvider

9.哈希值
--------
哈希算法将任意长度的二进制值映射为固定长度的较小二进制值,
这个小的二进制值称为哈希值。
哈希值是一段数据唯一且极其紧凑的数值表示形式。
如果散列一段明文而且哪怕只更改该段落的一个字母,
随后的哈希计算都将产生不同的值。
要找到散列为同一个值的两个不同的输入,在计算上是不可能的。

消息身份验证代码 (MAC) 哈希函数通常与数字签名一起用于对数据进行签名,
而消息检测代码 (MDC) 哈希函数则用于数据完整性。

双方(小红和小明)可按下面的方式使用哈希函数来确保数据的完整性。
如果小红对小明编写一条消息并创建该消息的哈希,
则小明可以在稍后散列该消息并将他的哈希与原始哈希进行比较。
如果两个哈希值相同,则该消息没有被更改;
如果值不相同,则该消息在小红编写它之后已被更改。
为了使此系统发挥作用,
小红必须对除小明外的所有人保密原始的哈希值。

10.  .NET Framework 提供以下实现数字签名算法的类:
--------------------------------
HMACSHA1

MACTripleDES

MD5CryptoServiceProvider

SHA1Managed

SHA256Managed

SHA384Managed

SHA512Managed

11. 随机数生成
-----------
随机数生成是许多加密操作不可分割的组成部分。
例如,加密密钥需要尽可能地随机,以便使生成的密钥很难再现。
加密随机数生成器必须生成无法以计算方法推算出(低于 p < .05 的概率)的输出;
即,任何推算下一个输出位的方法不得比随机猜测具有更高的成功概率。

12.  .NET Framework 中的类使用随机数生成器生成加密密钥。
--------------
RNGCryptoServiceProvider 类是随机数生成器算法的实现。

[引]DESCryptoServiceProvider 类

下面的示例使用 DESCryptoServiceProvider 类将一些数据加密到内存,然后解密数据。

Visual Basic 复制代码
' 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.
Imports System
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography



Class CryptoMemoryStream

' Main method.
Public Shared Sub Main()
' Create a new DES key.
Dim key As New DESCryptoServiceProvider()

' Encrypt a string to a byte array.
Dim buffer As Byte() = Encrypt("This is some plaintext!", key)

' Decrypt the byte array back to a string.
Dim plaintext As String = Decrypt(buffer, key)

' Display the plaintext value to the console.
Console.WriteLine(plaintext)
End Sub 'Main


' Encrypt the string.
Public Shared Function Encrypt(PlainText As String, key As SymmetricAlgorithm) As Byte()
' Create a memory stream.
Dim ms As New MemoryStream()

' Create a CryptoStream using the memory stream and the
' CSP DES key.
Dim encStream As New CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write)

' Create a StreamWriter to write a string
' to the stream.
Dim sw As 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.
Dim buffer As Byte() = ms.ToArray()

' Close the memory stream.
ms.Close()

' Return the encrypted byte array.
Return buffer
End Function 'Encrypt


' Decrypt the byte array.
Public Shared Function Decrypt(CypherText() As Byte, key As SymmetricAlgorithm) As String
' Create a memory stream to the passed buffer.
Dim ms As New MemoryStream(CypherText)

' Create a CryptoStream using the memory stream and the
' CSP DES key.
Dim encStream As New CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read)

' Create a StreamReader for reading the stream.
Dim sr As New StreamReader(encStream)

' Read the stream as a string.
Dim val As String = sr.ReadLine()

' Close the streams.
sr.Close()
encStream.Close()
ms.Close()

Return val
End Function 'Decrypt
End Class 'CryptoMemoryStream


C# 复制代码
// 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;
}
}


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:23 freeliver54

[引]RC2CryptoServiceProvider 类
下面的代码示例对一个字符串进行加密然后解密。

Visual Basic 复制代码
Imports System
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography



Module MyMainModule

Sub Main()

' Create a new instance of the RC2CryptoServiceProvider class
' and automatically generate a Key and IV.
Dim rc2CSP As New RC2CryptoServiceProvider()

Console.WriteLine("Effective key size is {0} bits.", rc2CSP.EffectiveKeySize)

' Get the key and IV.
Dim key As Byte() = rc2CSP.Key
Dim IV As Byte() = rc2CSP.IV

' Get an encryptor.
Dim encryptor As ICryptoTransform = rc2CSP.CreateEncryptor(key, IV)

' Encrypt the data as an array of encrypted bytes in memory.
Dim msEncrypt As New MemoryStream()
Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)

' Convert the data to a byte array.
Dim original As String = "Here is some data to encrypt."
Dim toEncrypt As Byte() = Encoding.ASCII.GetBytes(original)

' Write all data to the crypto stream and flush it.
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)
csEncrypt.FlushFinalBlock()

' Get the encrypted array of bytes.
Dim encrypted As Byte() = msEncrypt.ToArray()

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This is where the data could be transmitted or saved.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'Get a decryptor that uses the same key and IV as the encryptor.
Dim decryptor As ICryptoTransform = rc2CSP.CreateDecryptor(key, IV)

' Now decrypt the previously encrypted message using the decryptor
' obtained in the above step.
Dim msDecrypt As New MemoryStream(encrypted)
Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)

Dim fromEncrypt(toEncrypt.Length) As Byte

' Read the data out of the crypto stream.
csDecrypt.Read(fromEncrypt, 0, toEncrypt.Length)

' Convert the byte array back into a string.
Dim roundtrip As String = Encoding.ASCII.GetString(fromEncrypt)

' Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original)
Console.WriteLine("Round Trip: {0}", roundtrip)

Console.ReadLine()

End Sub
End Module


C# 复制代码
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace RC2CryptoServiceProvider_Examples
{
class MyMainClass
{
public static void Main()
{

// Create a new instance of the RC2CryptoServiceProvider class
// and automatically generate a Key and IV.
RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();

Console.WriteLine("Effective key size is {0} bits.", rc2CSP.EffectiveKeySize);

// Get the key and IV.
byte[] key = rc2CSP.Key;
byte[] IV = rc2CSP.IV;

// Get an encryptor.
ICryptoTransform encryptor = rc2CSP.CreateEncryptor(key, IV);

// Encrypt the data as an array of encrypted bytes in memory.
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

// Convert the data to a byte array.
string original = "Here is some data to encrypt.";
byte[] toEncrypt = Encoding.ASCII.GetBytes(original);

// Write all data to the crypto stream and flush it.
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();

// Get the encrypted array of bytes.
byte[] encrypted = msEncrypt.ToArray();

///////////////////////////////////////////////////////
// This is where the data could be transmitted or saved.
///////////////////////////////////////////////////////

//Get a decryptor that uses the same key and IV as the encryptor.
ICryptoTransform decryptor = rc2CSP.CreateDecryptor(key, IV);

// Now decrypt the previously encrypted message using the decryptor
// obtained in the above step.
MemoryStream msDecrypt = new MemoryStream(encrypted);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

byte[] fromEncrypt = new byte[toEncrypt.Length];

// Read the data out of the crypto stream.
csDecrypt.Read(fromEncrypt, 0, toEncrypt.Length);

// Convert the byte array back into a string.
String roundtrip = Encoding.ASCII.GetString(fromEncrypt);

// Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);

Console.ReadLine();
}
}
}


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:26 freeliver54

[引]RijndaelManaged 类

Visual Basic 复制代码
Imports System
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography

Namespace RijndaelManaged_Examples
Class MyMainClass
Public Shared Sub Main()
Dim original As String = "This is a much longer string of data than a public/private key algorithm will accept."
Dim roundtrip As String
Dim textConverter As New ASCIIEncoding()
Dim myRijndael As New RijndaelManaged()
Dim fromEncrypt() As Byte
Dim encrypted() As Byte
Dim toEncrypt() As Byte
Dim key() As Byte
Dim IV() As Byte

'Create a new key and initialization vector.
myRijndael.GenerateKey()
myRijndael.GenerateIV()

'Get the key and IV.
key = myRijndael.Key
IV = myRijndael.IV

'Get an encryptor.
Dim encryptor As ICryptoTransform = myRijndael.CreateEncryptor(key, IV)

'Encrypt the data.
Dim msEncrypt As New MemoryStream()
Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)

'Convert the data to a byte array.
toEncrypt = textConverter.GetBytes(original)

'Write all data to the crypto stream and flush it.
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)
csEncrypt.FlushFinalBlock()

'Get encrypted array of bytes.
encrypted = msEncrypt.ToArray()

'This is where the message would be transmitted to a recipient
' who already knows your secret key. Optionally, you can
' also encrypt your secret key using a public key algorithm
' and pass it to the mesage recipient along with the RijnDael
' encrypted message.
'Get a decryptor that uses the same key and IV as the encryptor.
Dim decryptor As ICryptoTransform = myRijndael.CreateDecryptor(key, IV)

'Now decrypt the previously encrypted message using the decryptor
' obtained in the above step.
Dim msDecrypt As New MemoryStream(encrypted)
Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)

fromEncrypt = New Byte(encrypted.Length) {}

'Read the data out of the crypto stream.
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)

'Convert the byte array back into a string.
roundtrip = textConverter.GetString(fromEncrypt)

'Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original)
Console.WriteLine("Round Trip: {0}", roundtrip)
End Sub 'Main
End Class 'MyMainClass
End Namespace 'RijndaelManaged_Examples


C# 复制代码
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace RijndaelManaged_Examples
{
class MyMainClass
{
public static void Main()
{
string original = "This is a much longer string of data than a public/private key algorithm will accept.";
string roundtrip;
ASCIIEncoding textConverter = new ASCIIEncoding();
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] fromEncrypt;
byte[] encrypted;
byte[] toEncrypt;
byte[] key;
byte[] IV;

//Create a new key and initialization vector.
myRijndael.GenerateKey();
myRijndael.GenerateIV();

//Get the key and IV.
key = myRijndael.Key;
IV = myRijndael.IV;

//Get an encryptor.
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);

//Encrypt the data.
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

//Convert the data to a byte array.
toEncrypt = textConverter.GetBytes(original);

//Write all data to the crypto stream and flush it.
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();

//Get encrypted array of bytes.
encrypted = msEncrypt.ToArray();

//This is where the message would be transmitted to a recipient
// who already knows your secret key. Optionally, you can
// also encrypt your secret key using a public key algorithm
// and pass it to the mesage recipient along with the RijnDael
// encrypted message.

//Get a decryptor that uses the same key and IV as the encryptor.
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

//Now decrypt the previously encrypted message using the decryptor
// obtained in the above step.
MemoryStream msDecrypt = new MemoryStream(encrypted);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

fromEncrypt = new byte[encrypted.Length];

//Read the data out of the crypto stream.
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

//Convert the byte array back into a string.
roundtrip = textConverter.GetString(fromEncrypt);

//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
}


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:27 freeliver54

[引]TripleDESCryptoServiceProvider 类
下面的代码示例创建一个 TripleDESCryptoServiceProvider 对象并使用该对象加密和解密文件中的数据。

Visual Basic 复制代码
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module TrippleDESCSPSample

Sub Main()
Try
' Create a new TripleDESCryptoServiceProvider object
' to generate a key and initialization vector (IV).
Dim tDESalg As New TripleDESCryptoServiceProvider

' Create a string to encrypt.
Dim sData As String = "Here is some data to encrypt."
Dim FileName As String = "CText.txt"

' Encrypt text to a file using the file name, key, and IV.
EncryptTextToFile(sData, FileName, tDESalg.Key, tDESalg.IV)

' Decrypt the text from a file using the file name, key, and IV.
Dim Final As String = DecryptTextFromFile(FileName, tDESalg.Key, tDESalg.IV)

' Display the decrypted string to the console.
Console.WriteLine(Final)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub


Sub EncryptTextToFile(ByVal Data As String, ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte)
Try
' Create or open the specified file.
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)

' Create a CryptoStream using the FileStream
' and the passed key and initialization vector (IV).
Dim cStream As New CryptoStream(fStream, _
New TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV), _
CryptoStreamMode.Write)

' Create a StreamWriter using the CryptoStream.
Dim sWriter As New StreamWriter(cStream)

' Write the data to the stream
' to encrypt it.
sWriter.WriteLine(Data)

' Close the streams and
' close the file.
sWriter.Close()
cStream.Close()
fStream.Close()
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Catch e As UnauthorizedAccessException
Console.WriteLine("A file error occurred: {0}", e.Message)
End Try
End Sub


Function DecryptTextFromFile(ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte) As String
Try
' Create or open the specified file.
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)

' Create a CryptoStream using the FileStream
' and the passed key and initialization vector (IV).
Dim cStream As New CryptoStream(fStream, _
New TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), _
CryptoStreamMode.Read)

' Create a StreamReader using the CryptoStream.
Dim sReader As New StreamReader(cStream)

' Read the data from the stream
' to decrypt it.
Dim val As String = sReader.ReadLine()

' Close the streams and
' close the file.
sReader.Close()
cStream.Close()
fStream.Close()

' Return the string.
Return val
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Return Nothing
Catch e As UnauthorizedAccessException
Console.WriteLine("A file error occurred: {0}", e.Message)
Return Nothing
End Try
End Function
End Module


C# 复制代码
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

class TrippleDESCSPSample
{

static void Main()
{
try
{
// Create a new TripleDESCryptoServiceProvider object
// to generate a key and initialization vector (IV).
TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();

// Create a string to encrypt.
string sData = "Here is some data to encrypt.";
string FileName = "CText.txt";

// Encrypt text to a file using the file name, key, and IV.
EncryptTextToFile(sData, FileName, tDESalg.Key, tDESalg.IV);

// Decrypt the text from a file using the file name, key, and IV.
string Final = DecryptTextFromFile(FileName, tDESalg.Key, tDESalg.IV);

// Display the decrypted string to the console.
Console.WriteLine(Final);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

}

public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
{
try
{
// Create or open the specified file.
FileStream fStream = File.Open(FileName,FileMode.OpenOrCreate);

// Create a CryptoStream using the FileStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream(fStream,
new TripleDESCryptoServiceProvider().CreateEncryptor(Key,IV),
CryptoStreamMode.Write);

// Create a StreamWriter using the CryptoStream.
StreamWriter sWriter = new StreamWriter(cStream);

// Write the data to the stream
// to encrypt it.
sWriter.WriteLine(Data);

// Close the streams and
// close the file.
sWriter.Close();
cStream.Close();
fStream.Close();
}
catch(CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
}
catch(UnauthorizedAccessException e)
{
Console.WriteLine("A file access error occurred: {0}", e.Message);
}

}

public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV)
{
try
{
// Create or open the specified file.
FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

// Create a CryptoStream using the FileStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream(fStream,
new TripleDESCryptoServiceProvider().CreateDecryptor(Key,IV),
CryptoStreamMode.Read);

// Create a StreamReader using the CryptoStream.
StreamReader sReader = new StreamReader(cStream);

// Read the data from the stream
// to decrypt it.
string val = sReader.ReadLine();

// Close the streams and
// close the file.
sReader.Close();
cStream.Close();
fStream.Close();

// Return the string.
return val;
}
catch(CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
catch(UnauthorizedAccessException e)
{
Console.WriteLine("A file access error occurred: {0}", e.Message);
return null;
}
}
}


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:28 freeliver54

[引]DSACryptoServiceProvider 类

下面的代码示例使用 DSACryptoServiceProvider 类创建哈希值的数字签名,然后验证签名。

Visual Basic 复制代码
Imports System
Imports System.Security.Cryptography

_

Class DSACSPSample


Shared Sub Main()
Try
'Create a new instance of DSACryptoServiceProvider to generate
'a new key pair.
Dim DSA As New DSACryptoServiceProvider()

'The hash value to sign.
Dim HashValue As Byte() = {59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135}

'The value to hold the signed value.
Dim SignedHashValue As Byte() = DSASignHash(HashValue, DSA.ExportParameters(True), "SHA1")

'Verify the hash and display the results.
If DSAVerifyHash(HashValue, SignedHashValue, DSA.ExportParameters(False), "SHA1") Then
Console.WriteLine("The hash value was verified.")
Else
Console.WriteLine("The hash value was not verified.")
End If


Catch e As ArgumentNullException
Console.WriteLine(e.Message)
End Try
End Sub


Public Shared Function DSASignHash(ByVal HashToSign() As Byte, ByVal DSAKeyInfo As DSAParameters, ByVal HashAlg As String) As Byte()
Try
'Create a new instance of DSACryptoServiceProvider.
Dim DSA As New DSACryptoServiceProvider()

'Import the key information.
DSA.ImportParameters(DSAKeyInfo)

'Create an DSASignatureFormatter object and pass it the
'DSACryptoServiceProvider to transfer the private key.
Dim DSAFormatter As New DSASignatureFormatter(DSA)

'Set the hash algorithm to the passed value.
DSAFormatter.SetHashAlgorithm(HashAlg)

'Create a signature for HashValue and return it.
Return DSAFormatter.CreateSignature(HashToSign)
Catch e As CryptographicException
Console.WriteLine(e.Message)

Return Nothing
End Try
End Function


Public Shared Function DSAVerifyHash(ByVal HashValue() As Byte, ByVal SignedHashValue() As Byte, ByVal DSAKeyInfo As DSAParameters, ByVal HashAlg As String) As Boolean
Try
'Create a new instance of DSACryptoServiceProvider.
Dim DSA As New DSACryptoServiceProvider()

'Import the key information.
DSA.ImportParameters(DSAKeyInfo)

'Create an DSASignatureDeformatter object and pass it the
'DSACryptoServiceProvider to transfer the private key.
Dim DSADeformatter As New DSASignatureDeformatter(DSA)

'Set the hash algorithm to the passed value.
DSADeformatter.SetHashAlgorithm(HashAlg)

'Verify signature and return the result.
Return DSADeformatter.VerifySignature(HashValue, SignedHashValue)
Catch e As CryptographicException
Console.WriteLine(e.Message)

Return False
End Try
End Function
End Class



C# 复制代码
using System;
using System.Security.Cryptography;

class DSACSPSample
{

static void Main()
{
try
{
//Create a new instance of DSACryptoServiceProvider to generate
//a new key pair.
DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

//The hash value to sign.
byte[] HashValue = {59,4,248,102,77,97,142,201,210,12,224,93,25,41,100,197,213,134,130,135};

//The value to hold the signed value.
byte[] SignedHashValue = DSASignHash(HashValue, DSA.ExportParameters(true), "SHA1");

//Verify the hash and display the results.
if(DSAVerifyHash(HashValue, SignedHashValue, DSA.ExportParameters(false), "SHA1"))
{
Console.WriteLine("The hash value was verified.");
}
else
{
Console.WriteLine("The hash value was not verified.");
}


}
catch(ArgumentNullException e)
{
Console.WriteLine(e.Message);
}
}

public static byte[] DSASignHash(byte[] HashToSign, DSAParameters DSAKeyInfo, string HashAlg)
{
try
{
//Create a new instance of DSACryptoServiceProvider.
DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

//Import the key information.
DSA.ImportParameters(DSAKeyInfo);

//Create an DSASignatureFormatter object and pass it the
//DSACryptoServiceProvider to transfer the private key.
DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);

//Set the hash algorithm to the passed value.
DSAFormatter.SetHashAlgorithm(HashAlg);

//Create a signature for HashValue and return it.
return DSAFormatter.CreateSignature(HashToSign);
}
catch(CryptographicException e)
{
Console.WriteLine(e.Message);

return null;
}

}

public static bool DSAVerifyHash(byte[] HashValue, byte[] SignedHashValue, DSAParameters DSAKeyInfo, string HashAlg)
{
try
{
//Create a new instance of DSACryptoServiceProvider.
DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

//Import the key information.
DSA.ImportParameters(DSAKeyInfo);

//Create an DSASignatureDeformatter object and pass it the
//DSACryptoServiceProvider to transfer the private key.
DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);

//Set the hash algorithm to the passed value.
DSADeformatter.SetHashAlgorithm(HashAlg);

//Verify signature and return the result.
return DSADeformatter.VerifySignature(HashValue, SignedHashValue);
}
catch(CryptographicException e)
{
Console.WriteLine(e.Message);

return false;
}

}

}


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:30 freeliver54

[引]RSACryptoServiceProvider 类

下面的代码示例使用 RSACryptoServiceProvider 类将一个字符串加密为一个字节数组,然后将这些字节解密为字符串。

Visual Basic 复制代码
Imports System
Imports System.Security.Cryptography
Imports System.Text

_

Class RSACSPSample


Shared Sub Main()
Try
'Create a UnicodeEncoder to convert between byte array and string.
Dim ByteConverter As New UnicodeEncoding()

'Create byte arrays to hold original, encrypted, and decrypted data.
Dim dataToEncrypt As Byte() = ByteConverter.GetBytes("Data to Encrypt")
Dim encryptedData() As Byte
Dim decryptedData() As Byte

'Create a new instance of RSACryptoServiceProvider to generate
'public and private key data.
Dim RSA As New RSACryptoServiceProvider()

'Pass the data to ENCRYPT, the public key information
'(using RSACryptoServiceProvider.ExportParameters(false),
'and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(False), False)

'Pass the data to DECRYPT, the private key information
'(using RSACryptoServiceProvider.ExportParameters(true),
'and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(True), False)

'Display the decrypted plaintext to the console.
Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData))
Catch e As ArgumentNullException
'Catch this exception in case the encryption did
'not succeed.
Console.WriteLine("Encryption failed.")
End Try
End Sub


Public Shared Function RSAEncrypt(ByVal DataToEncrypt() As Byte, ByVal RSAKeyInfo As RSAParameters, ByVal DoOAEPPadding As Boolean) As Byte()
Try
'Create a new instance of RSACryptoServiceProvider.
Dim RSA As New RSACryptoServiceProvider()

'Import the RSA Key information. This only needs
'toinclude the public key information.
RSA.ImportParameters(RSAKeyInfo)

'Encrypt the passed byte array and specify OAEP padding.
'OAEP padding is only available on Microsoft Windows XP or
'later.
Return RSA.Encrypt(DataToEncrypt, DoOAEPPadding)
'Catch and display a CryptographicException
'to the console.
Catch e As CryptographicException
Console.WriteLine(e.Message)

Return Nothing
End Try
End Function


Public Shared Function RSADecrypt(ByVal DataToDecrypt() As Byte, ByVal RSAKeyInfo As RSAParameters, ByVal DoOAEPPadding As Boolean) As Byte()
Try
'Create a new instance of RSACryptoServiceProvider.
Dim RSA As New RSACryptoServiceProvider()

'Import the RSA Key information. This needs
'to include the private key information.
RSA.ImportParameters(RSAKeyInfo)

'Decrypt the passed byte array and specify OAEP padding.
'OAEP padding is only available on Microsoft Windows XP or
'later.
Return RSA.Decrypt(DataToDecrypt, DoOAEPPadding)
'Catch and display a CryptographicException
'to the console.
Catch e As CryptographicException
Console.WriteLine(e.ToString())

Return Nothing
End Try
End Function
End Class


C# 复制代码
using System;
using System.Security.Cryptography;
using System.Text;

class RSACSPSample
{

static void Main()
{
try
{
//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter = new UnicodeEncoding();

//Create byte arrays to hold original, encrypted, and decrypted data.
byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt");
byte[] encryptedData;
byte[] decryptedData;

//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

//Pass the data to ENCRYPT, the public key information
//(using RSACryptoServiceProvider.ExportParameters(false),
//and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(dataToEncrypt,RSA.ExportParameters(false), false);

//Pass the data to DECRYPT, the private key information
//(using RSACryptoServiceProvider.ExportParameters(true),
//and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(encryptedData,RSA.ExportParameters(true), false);

//Display the decrypted plaintext to the console.
Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
}
catch(ArgumentNullException)
{
//Catch this exception in case the encryption did
//not succeed.
Console.WriteLine("Encryption failed.");

}
}

static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

//Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(RSAKeyInfo);

//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
//Catch and display a CryptographicException
//to the console.
catch(CryptographicException e)
{
Console.WriteLine(e.Message);

return null;
}

}

static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo,bool DoOAEPPadding)
{
try
{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);

//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
//Catch and display a CryptographicException
//to the console.
catch(CryptographicException e)
{
Console.WriteLine(e.ToString());

return null;
}

}
}


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:31 freeliver54

[引]HMACSHA1 类

HMACSHA1 是从 SHA1 哈希函数构造的一种键控哈希算法,被用作 HMAC(基于哈希的消息验证代码)。此 HMAC 进程将密钥与消息数据混合,使用哈希函数对混合结果进行哈希计算,将所得哈希值与该密钥混合,然后再次应用哈希函数。输出的哈希值长度为 160 位。

在发送方和接收方共享机密密钥的前提下,HMAC 可用于确定通过不安全信道发送的消息是否已被篡改。发送方计算原始数据的哈希值,并将原始数据和哈希值放在一个消息中同时传送。接收方重新计算所接收消息的哈希值,并检查计算所得的 HMAC 是否与传送的 HMAC 匹配。

因为更改消息和重新生成正确的哈希值需要密钥,所以对数据或哈希值的任何更改都会导致不匹配。因此,如果原始的哈希值与计算得出的哈希值相匹配,则消息通过身份验证。

SHA-1(安全哈希算法,也称为 SHS、安全哈希标准)是由美国政府发布的一种加密哈希算法。它将从任意长度的字符串生成 160 位的哈希值。

HMACSHA1 接受任何大小的密钥,并产生长度为 160 位的哈希序列。

示例
下面的代码示例演示如何使用 HMACSHA1 编码文件以及之后如何解码该文件。

C# 复制代码
using System;
using System.IO;
using System.Security.Cryptography;

public class HMACSHA1example
{
// Computes a keyed hash for a source file, creates a target file with the keyed hash
// prepended to the contents of the source file, then decrypts the file and compares
// the source and the decrypted files.
public static void EncodeFile(byte[] key, String sourceFile, String destFile)
{
// Initialize the keyed hash object.
HMACSHA1 myhmacsha1 = new HMACSHA1(key);
FileStream inStream = new FileStream(sourceFile, FileMode.Open);
FileStream outStream = new FileStream(destFile, FileMode.Create);
// Compute the hash of the input file.
byte[] hashValue = myhmacsha1.ComputeHash(inStream);
// Reset inStream to the beginning of the file.
inStream.Position = 0;
// Write the computed hash value to the output file.
outStream.Write(hashValue, 0, hashValue.Length);
// Copy the contents of the sourceFile to the destFile.
int bytesRead;
// read 1K at a time
byte[] buffer = new byte[1024];
do
{
// Read from the wrapping CryptoStream.
bytesRead = inStream.Read(buffer,0,1024);
outStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
myhmacsha1.Clear();
// Close the streams
inStream.Close();
outStream.Close();
return;
} // end EncodeFile


// Decrypt the encoded file and compare to original file.
public static bool DecodeFile(byte[] key, String sourceFile)
{
// Initialize the keyed hash object.
HMACSHA1 hmacsha1 = new HMACSHA1(key);
// Create an array to hold the keyed hash value read from the file.
byte[] storedHash = new byte[hmacsha1.HashSize/8];
// Create a FileStream for the source file.
FileStream inStream = new FileStream(sourceFile, FileMode.Open);
// Read in the storedHash.
inStream.Read(storedHash, 0, storedHash.Length);
// Compute the hash of the remaining contents of the file.
// The stream is properly positioned at the beginning of the content,
// immediately after the stored hash value.
byte[] computedHash = hmacsha1.ComputeHash(inStream);
// compare the computed hash with the stored value
for (int i =0; i < storedHash.Length; i++)
{
if (computedHash[i] != storedHash[i])
{
Console.WriteLine("Hash values differ! Encoded file has been tampered with!");
return false;
}
}
Console.WriteLine("Hash values agree -- no tampering occurred.");
return true;
} //end DecodeFile

private const string usageText = "Usage: HMACSHA1 inputfile.txt encryptedfile.hsh/nYou must specify the two file names. Only the first file must exist./n";
public static void Main(string[] Fileargs)
{
//If no file names are specified, write usage text.
if (Fileargs.Length < 2)
{
Console.WriteLine(usageText);
}
else
{
try
{
// Create a random key using a random number generator. This would be the
// secret key shared by sender and receiver.
byte[] secretkey = new Byte[64];
//RNGCryptoServiceProvider is an implementation of a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// The array is now filled with cryptographically strong random bytes.
rng.GetBytes(secretkey);

// Use the secret key to encode the message file.
EncodeFile(secretkey, Fileargs[0], Fileargs[1]);

// Take the encoded file and decode
DecodeFile(secretkey, Fileargs[1]);
}
catch (IOException e)
{
Console.WriteLine("Error: File not found",e);
}
} //end if-else

} //end main
} //end class


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:32 freeliver54

[引]MACTripleDES 类

在发送方和接收方共享机密密钥的前提下,MAC 可用于确定通过不安全信道发送的消息是否已被篡改。发送方计算原始数据的 MAC,然后将 MAC 和原始数据作为单个消息发送。接收方重新计算接收到的消息的 MAC,检查计算所得的 MAC 是否与传送的 MAC 匹配。

数据或 MAC 的任何更改都将产生不匹配,因为更改消息和重新产生正确的 MAC 需要知道机密密钥。因此,如果代码匹配,则消息通过了身份验证。

MACTripleDES 使用长度为 16 或 24 字节的密钥,并产生长度为 8 字节的哈希序列。

示例
下节包含代码示例。第一个示例使用 TripleDES 哈希算法计算 data 的 MAC,并将其存储在 result 中。第二个示例演示如何使用 MACTripleDES 类的每个成员。

示例 1

此示例假定存在一个预定义的常数 DATA_SIZE。

Visual Basic 复制代码
Dim data(DATA_SIZE) As Byte
Dim key(24) As Byte

Dim mac3des As New MACTripleDES(key)

Dim result As Byte() = mac3des.ComputeHash(data)


C# 复制代码
byte[] data = new byte[DATA_SIZE];
byte[] key = new byte[24];

MACTripleDES mac3des = new MACTripleDES(key);

byte[] result = mac3des.ComputeHash(data);


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:33 freeliver54

[引]MD5CryptoServiceProvider 类

下面的代码示例计算 data 的 MD5 哈希值并将其返回。

Visual Basic 复制代码
Function MD5hash(data() As Byte) As Byte()
' This is one implementation of the abstract class MD5.
Dim md5 As New MD5CryptoServiceProvider()

Dim result As Byte() = md5.ComputeHash(data)

Return result
End Function


C# 复制代码
byte[] MD5hash (byte[] data)
{
// This is one implementation of the abstract class MD5.
MD5 md5 = new MD5CryptoServiceProvider();

byte[] result = md5.ComputeHash(data);

return result;
}


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:35 freeliver54

[引]SHA1Managed 类
下面的示例计算 data 的 SHA1Managed 哈希值,并将它存储在 result 中。
此示例假定存在一个预定义的常数 DATA_SIZE。

Visual Basic 复制代码
Dim data(DATA_SIZE) As Byte
Dim result() As Byte
Dim shaM As New SHA1Managed()
result = shaM.ComputeHash(data)


C# 复制代码
byte[] data = new byte[DATA_SIZE];
byte[] result;
SHA1 shaM = new SHA1Managed();
result = shaM.ComputeHash(data);



  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:36 freeliver54

[引]SHA256Managed 类
下面的示例计算 data 的 SHA256Managed 哈希值,并将它存储在 result 中。
此示例假定存在一个预定义的常数 DATA_SIZE。

Visual Basic 复制代码
Dim data(DATA_SIZE) As Byte
Dim result() As Byte

Dim shaM As New SHA256Managed()
result = shaM.ComputeHash(data)


C# 复制代码
byte[] data = new byte[DATA_SIZE];
byte[] result;

SHA256 shaM = new SHA256Managed();
result = shaM.ComputeHash(data);


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:37 freeliver54

下面的示例计算 data 的 SHA384Managed 哈希值,并将它存储在 result 中。此示例假定存在一个预定义的常数 DATA_SIZE。

Visual Basic 复制代码
Dim data(DATA_SIZE) As Byte
Dim result() As Byte

Dim shaM As New SHA384Managed()
result = shaM.ComputeHash(data)


C# 复制代码
byte[] data = new byte[DATA_SIZE];
byte[] result;

SHA384 shaM = new SHA384Managed();
result = shaM.ComputeHash(data);


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:37 freeliver54

下面的示例计算 data 的 SHA512Managed 哈希值,并将它存储在 result 中。此示例假定存在一个预定义的常数 DATA_SIZE。

Visual Basic 复制代码
Dim data(DATA_SIZE) As Byte
Dim result() As Byte

Dim shaM As New SHA512Managed()
result = shaM.ComputeHash(data)


C# 复制代码
byte[] data = new byte[DATA_SIZE];
byte[] result;

SHA512 shaM = new SHA512Managed();
result = shaM.ComputeHash(data);


  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-03-08 19:38 freeliver54

下面的代码示例演示如何用 RNGCryptoServiceProvider 类创建随机数。

Visual Basic 复制代码
'The following sample uses the Cryptography class to simulate the roll of a dice.
Imports System
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography



Class RNGCSP

' Main method.
Public Shared Sub Main()
' Roll the dice 30 times and display
' the results to the console.
Dim x As Integer
For x = 0 To 30
Console.WriteLine(RollDice(6))
Next x
End Sub 'Main

' This method simulates a roll of the dice. The input parameter is the
' number of sides of the dice.
Public Shared Function RollDice(NumSides As Integer) As Integer
' Create a byte array to hold the random value.
Dim randomNumber(0) As Byte

' Create a new instance of the RNGCryptoServiceProvider.
Dim Gen As New RNGCryptoServiceProvider()

' Fill the array with a random value.
Gen.GetBytes(randomNumber)

' Convert the byte to an integer value to make the modulus operation easier.
Dim rand As Integer = Convert.ToInt32(randomNumber(0))

' Return the random number mod the number
' of sides. The possible values are zero-
' based, so we add one.
Return rand Mod NumSides + 1
End Function 'RollDice
End Class 'CryptoMemoryStream



C# 复制代码
//The following sample uses the Cryptography class to simulate the roll of a dice.

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

class RNGCSP
{
// Main method.
public static void Main()
{
// Roll the dice 30 times and display
// the results to the console.
for(int x = 0; x <= 30; x++)
Console.WriteLine(RollDice(6));
}

// This method simulates a roll of the dice. The input parameter is the
// number of sides of the dice.
public static int RollDice(int NumSides)
{
// Create a byte array to hold the random value.
byte[] randomNumber = new byte[1];

// Create a new instance of the RNGCryptoServiceProvider.
RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();

// Fill the array with a random value.
Gen.GetBytes(randomNumber);

// Convert the byte to an integer value to make the modulus operation easier.
int rand = Convert.ToInt32(randomNumber[0]);

// Return the random number mod the number
// of sides. The possible values are zero-
// based, so we add one.
return rand % NumSides + 1;
}
}



  回复  更多评论   

# re: [引]VS2005帮助文档 : 加密 概述 2007-04-09 10:50 freeliver54

[转]
using System;
using System.Text;
using System.Globalization;
using System.Security.Cryptography;
class DES
{
// 创建Key
public string GenerateKey()
{
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
// 加密字符串
public string EncryptString(string sInputString, string sKey)
{
byte [] data = Encoding.UTF8.GetBytes(sInputString);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
byte [] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return BitConverter.ToString(result);
}
// 解密字符串
public string DecryptString(string sInputString, string sKey)
{
string [] sInput = sInputString.Split("-".ToCharArray());
byte [] data = new byte[sInput.Length];
for(int i = 0; i < sInput.Length; i++)
{
data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateDecryptor();
byte [] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return Encoding.UTF8.GetString(result);
}
}
class Test
{
static void Main()
{
DES des = new DES();
string key = des.GenerateKey();
string s0 = "中国软件 - youkuaiyun.com";
string s1 = des.EncryptString(s0, key);
string s2 = des.DecryptString(s1, key);
Console.WriteLine("原串: [{0}]", s0);
Console.WriteLine("加密: [{0}]", s1);
Console.WriteLine("解密: [{0}]", s2);
}
}
/* 程序输出:
原串: [中国软件 - youkuaiyun.com]
加密: [E8-30-D0-F2-2F-66-52-14-45-9A-DC-C5-85-E7-62-9B-AD-B7-82-CF-A8-0A-59-77]
解密: [中国软件 - youkuaiyun.com]
*/

内容概要:本文探讨了在MATLAB/SimuLink环境中进行三相STATCOM(静态同步补偿器)无功补偿的技术方法及其仿真过程。首先介绍了STATCOM作为无功功率补偿装置的工作原理,即通过调节交流电压的幅值和相位来实现对无功功率的有效管理。接着详细描述了在MATLAB/SimuLink平台下构建三相STATCOM仿真模型的具体步骤,包括创建新模型、添加电源和负载、搭建主电路、加入控制模块以及完成整个电路的连接。然后阐述了如何通过对STATCOM输出电压和电流的精确调控达到无功补偿的目的,并展示了具体的仿真结果分析方法,如读取仿真数据、提取关键参数、绘制无功功率变化曲线等。最后指出,这种技术可以显著提升电力系统的稳定性与电能质量,展望了STATCOM在未来的发展潜力。 适合人群:电气工程专业学生、从事电力系统相关工作的技术人员、希望深入了解无功补偿技术的研究人员。 使用场景及目标:适用于想要掌握MATLAB/SimuLink软件操作技能的人群,特别是那些专注于电力电子领域的从业者;旨在帮助他们学会建立复杂的电力系统仿真模型,以便更好地理解STATCOM的工作机制,进而优化实际项目中的无功补偿方案。 其他说明:文中提供的实例代码可以帮助读者直观地了解如何从零开始构建一个完整的三相STATCOM仿真环境,并通过图形化的方式展示无功补偿的效果,便于进一步的学习与研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值