RijndaelManaged Класс
Определение
public ref class RijndaelManaged sealed : System::Security::Cryptography::Rijndael
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public sealed class RijndaelManaged : System.Security.Cryptography.Rijndael
public sealed class RijndaelManaged : System.Security.Cryptography.Rijndael
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class RijndaelManaged : System.Security.Cryptography.Rijndael
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
type RijndaelManaged = class
inherit Rijndael
type RijndaelManaged = class
inherit Rijndael
[<System.Runtime.InteropServices.ComVisible(true)>]
type RijndaelManaged = class
inherit Rijndael
Public NotInheritable Class RijndaelManaged
Inherits Rijndael
- Наследование
- Атрибуты
Примеры
В следующем примере демонстрируется шифрование и расшифровка демонстрационных данных с помощью RijndaelManaged
класса.The following example demonstrates how to encrypt and decrypt sample data using the RijndaelManaged
class.
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Security::Cryptography;
class RijndaelMemoryExample
{
public:
static array<Byte>^ encryptStringToBytes_AES(String^ plainText, array<Byte>^ Key, array<Byte>^ IV)
{
// Check arguments.
if (!plainText || plainText->Length <= 0)
throw gcnew ArgumentNullException("plainText");
if (!Key || Key->Length <= 0)
throw gcnew ArgumentNullException("Key");
if (!IV || IV->Length <= 0)
throw gcnew ArgumentNullException("IV");
// Declare the streams used
// to encrypt to an in memory
// array of bytes.
MemoryStream^ msEncrypt;
CryptoStream^ csEncrypt;
StreamWriter^ swEncrypt;
// Declare the RijndaelManaged object
// used to encrypt the data.
RijndaelManaged^ aesAlg;
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = gcnew RijndaelManaged();
aesAlg->Padding = PaddingMode::PKCS7;
aesAlg->Key = Key;
aesAlg->IV = IV;
// Create an encryptor to perform the stream transform.
ICryptoTransform^ encryptor = aesAlg->CreateEncryptor(aesAlg->Key, aesAlg->IV);
// Create the streams used for encryption.
msEncrypt = gcnew MemoryStream();
csEncrypt = gcnew CryptoStream(msEncrypt, encryptor, CryptoStreamMode::Write);
swEncrypt = gcnew StreamWriter(csEncrypt);
//Write all data to the stream.
swEncrypt->Write(plainText);
swEncrypt->Flush();
csEncrypt->FlushFinalBlock();
msEncrypt->Flush();
}
finally
{
// Clean things up.
// Close the streams.
if(swEncrypt)
swEncrypt->Close();
if (csEncrypt)
csEncrypt->Close();
// Clear the RijndaelManaged object.
if (aesAlg)
aesAlg->Clear();
}
// Return the encrypted bytes from the memory stream.
return msEncrypt->ToArray();
}
static String^ decryptStringFromBytes_AES(array<Byte>^ cipherText, array<Byte>^ Key, array<Byte>^ IV)
{
// Check arguments.
if (!cipherText || cipherText->Length <= 0)
throw gcnew ArgumentNullException("cipherText");
if (!Key || Key->Length <= 0)
throw gcnew ArgumentNullException("Key");
if (!IV || IV->Length <= 0)
throw gcnew ArgumentNullException("IV");
// TDeclare the streams used
// to decrypt to an in memory
// array of bytes.
MemoryStream^ msDecrypt;
CryptoStream^ csDecrypt;
StreamReader^ srDecrypt;
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged^ aesAlg;
// Declare the string used to hold
// the decrypted text.
String^ plaintext;
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = gcnew RijndaelManaged();
aesAlg->Padding = PaddingMode::PKCS7;
aesAlg->Key = Key;
aesAlg->IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform^ decryptor = aesAlg->CreateDecryptor(aesAlg->Key, aesAlg->IV);
// Create the streams used for decryption.
msDecrypt = gcnew MemoryStream(cipherText);
csDecrypt = gcnew CryptoStream(msDecrypt, decryptor, CryptoStreamMode::Read);
srDecrypt = gcnew StreamReader(csDecrypt);
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt->ReadToEnd();
}
finally
{
// Clean things up.
// Close the streams.
if (srDecrypt)
srDecrypt->Close();
if (csDecrypt)
csDecrypt->Close();
if (msDecrypt)
msDecrypt->Close();
// Clear the RijndaelManaged object.
if (aesAlg)
aesAlg->Clear();
}
return plaintext;
}
};
int main()
{
try
{
String^ original = "Here is some data to encrypt!";
// Create a new instance of the RijndaelManaged
// class. This generates a new key and initialization
// vector (IV).
RijndaelManaged^ myRijndael = gcnew RijndaelManaged();
// Encrypt the string to an array of bytes.
array<Byte>^ encrypted = RijndaelMemoryExample::encryptStringToBytes_AES(original, myRijndael->Key, myRijndael->IV);
// Decrypt the bytes to a string.
String^ roundtrip = RijndaelMemoryExample::decryptStringFromBytes_AES(encrypted, myRijndael->Key, myRijndael->IV);
//Display the original data and the decrypted data.
Console::WriteLine("Original: {0}", original);
Console::WriteLine("Round Trip: {0}", roundtrip);
}
catch (Exception^ e)
{
Console::WriteLine("Error: {0}", e->Message);
}
return 0;
}
using System;
using System.IO;
using System.Security.Cryptography;
namespace RijndaelManaged_Example
{
class RijndaelExample
{
public static void Main()
{
try
{
string original = "Here is some data to encrypt!";
// Create a new instance of the RijndaelManaged
// class. This generates a new key and initialization
// vector (IV).
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.GenerateKey();
myRijndael.GenerateIV();
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
Imports System.IO
Imports System.Security.Cryptography
Class RijndaelExample
Public Shared Sub Main()
Try
Dim original As String = "Here is some data to encrypt!"
' Create a new instance of the RijndaelManaged
' class. This generates a new key and initialization
' vector (IV).
Using myRijndael As New RijndaelManaged()
myRijndael.GenerateKey()
myRijndael.GenerateIV()
' Encrypt the string to an array of bytes.
Dim encrypted As Byte() = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV)
' Decrypt the bytes to a string.
Dim roundtrip As String = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV)
'Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original)
Console.WriteLine("Round Trip: {0}", roundtrip)
End Using
Catch e As Exception
Console.WriteLine("Error: {0}", e.Message)
End Try
End Sub
Shared Function EncryptStringToBytes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
' Check arguments.
If plainText Is Nothing OrElse plainText.Length <= 0 Then
Throw New ArgumentNullException("plainText")
End If
If Key Is Nothing OrElse Key.Length <= 0 Then
Throw New ArgumentNullException("Key")
End If
If IV Is Nothing OrElse IV.Length <= 0 Then
Throw New ArgumentNullException("IV")
End If
Dim encrypted() As Byte
' Create an RijndaelManaged object
' with the specified key and IV.
Using rijAlg As New RijndaelManaged()
rijAlg.Key = Key
rijAlg.IV = IV
' Create an encryptor to perform the stream transform.
Dim encryptor As ICryptoTransform = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV)
' Create the streams used for encryption.
Using msEncrypt As New MemoryStream()
Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
Using swEncrypt As New StreamWriter(csEncrypt)
'Write all data to the stream.
swEncrypt.Write(plainText)
End Using
encrypted = msEncrypt.ToArray()
End Using
End Using
End Using
' Return the encrypted bytes from the memory stream.
Return encrypted
End Function 'EncryptStringToBytes
Shared Function DecryptStringFromBytes(ByVal cipherText() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
' Check arguments.
If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
Throw New ArgumentNullException("cipherText")
End If
If Key Is Nothing OrElse Key.Length <= 0 Then
Throw New ArgumentNullException("Key")
End If
If IV Is Nothing OrElse IV.Length <= 0 Then
Throw New ArgumentNullException("IV")
End If
' Declare the string used to hold
' the decrypted text.
Dim plaintext As String = Nothing
' Create an RijndaelManaged object
' with the specified key and IV.
Using rijAlg As New RijndaelManaged
rijAlg.Key = Key
rijAlg.IV = IV
' Create a decryptor to perform the stream transform.
Dim decryptor As ICryptoTransform = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV)
' Create the streams used for decryption.
Using msDecrypt As New MemoryStream(cipherText)
Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
Using srDecrypt As New StreamReader(csDecrypt)
' Read the decrypted bytes from the decrypting stream
' and place them in a string.
plaintext = srDecrypt.ReadToEnd()
End Using
End Using
End Using
End Using
Return plaintext
End Function 'DecryptStringFromBytes
End Class
Комментарии
Этот алгоритм поддерживает ключи длиной 128, 192 или 256 бит; по умолчанию используется значение 256 бит.This algorithm supports key lengths of 128, 192, or 256 bits; defaulting to 256 bits. В платформа .NET Framework этот алгоритм поддерживает размер блоков 128, 192 или 256 бит; по умолчанию используется значение 128 бит ( Aes совместимо).In .NET Framework, this algorithm supports block sizes of 128, 192, or 256 bits; defaulting to 128 bits (Aes-compatible). В .NET Core это то же самое, что и AES, и поддерживает только 128-разрядный размер блока.In .NET Core, it is the same as AES and supports only a 128-bit block size.
Важно!
RijndaelКласс является предшественником Aes алгоритма.The Rijndael class is the predecessor of the Aes algorithm. Вместо следует использовать Aes алгоритм Rijndael .You should use the Aes algorithm instead of Rijndael. Дополнительные сведения см. в записи различия между Rijndael и AES в блоге по безопасности .NET.For more information, see the entry The Differences Between Rijndael and AES in the .NET Security blog.
Конструкторы
RijndaelManaged() |
Инициализирует новый экземпляр класса RijndaelManaged.Initializes a new instance of the RijndaelManaged class. |
Поля
BlockSizeValue |
Представляет размер блока криптографической операции (в битах).Represents the block size, in bits, of the cryptographic operation. (Унаследовано от SymmetricAlgorithm) |
FeedbackSizeValue |
Представляет размер порции данных обратной связи для криптографической операции (в битах).Represents the feedback size, in bits, of the cryptographic operation. (Унаследовано от SymmetricAlgorithm) |
IVValue |
Представляет вектор инициализации (IV) для алгоритма симметричного шифрования.Represents the initialization vector (IV) for the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
KeySizeValue |
Представляет размер секретного ключа (в битах), используемого алгоритмом симметричного шифрования.Represents the size, in bits, of the secret key used by the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
KeyValue |
Представляет секретный ключ для алгоритма симметричного шифрования.Represents the secret key for the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
LegalBlockSizesValue |
Задает размеры блоков (в битах), которые поддерживаются алгоритмом симметричного шифрования.Specifies the block sizes, in bits, that are supported by the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
LegalKeySizesValue |
Задает размеры ключа (в битах), которые поддерживаются алгоритмом симметричного шифрования.Specifies the key sizes, in bits, that are supported by the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
ModeValue |
Представляет режим шифрования, используемый в алгоритме симметричного шифрования.Represents the cipher mode used in the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
PaddingValue |
Представляет режим заполнения, используемый в алгоритме симметричного шифрования.Represents the padding mode used in the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
Свойства
BlockSize |
Возвращает или задает размер блока криптографической операции (в битах).Gets or sets the block size, in bits, of the cryptographic operation. |
BlockSize |
Возвращает или задает размер блока криптографической операции (в битах).Gets or sets the block size, in bits, of the cryptographic operation. (Унаследовано от SymmetricAlgorithm) |
FeedbackSize |
Возвращает или задает размер ответа криптографической операции (в битах) для режимов шифрования "Обратная связь по шифру" (CFB) и "Выходная обратная связь" (OFB).Gets or sets the feedback size, in bits, of the cryptographic operation for the Cipher Feedback (CFB) and Output Feedback (OFB) cipher modes. (Унаследовано от SymmetricAlgorithm) |
IV |
Получает или задает вектор инициализации для алгоритма симметричного шифрования.Gets or sets the initialization vector (IV) to use for the symmetric algorithm. |
IV |
Получает или задает вектор инициализации (IV) для алгоритма симметричного шифрования.Gets or sets the initialization vector (IV) for the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
Key |
Получает или задает секретный ключ для алгоритма симметричного шифрования.Gets or sets the secret key used for the symmetric algorithm. |
Key |
Получает или задает секретный ключ для алгоритма симметричного шифрования.Gets or sets the secret key for the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
KeySize |
Получает или задает размер секретного ключа (в битах), используемого алгоритмом симметричного шифрования.Gets or sets the size, in bits, of the secret key used for the symmetric algorithm. |
KeySize |
Получает или задает размер секретного ключа (в битах), используемого алгоритмом симметричного шифрования.Gets or sets the size, in bits, of the secret key used by the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
LegalBlockSizes |
Получает размеры блоков (в битах), которые поддерживаются алгоритмом симметричного шифрования.Gets the block sizes, in bits, that are supported by the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
LegalKeySizes |
Возвращает размеры ключа (в битах), которые поддерживаются симметричным алгоритмом.Gets the key sizes, in bits, that are supported by the symmetric algorithm. |
LegalKeySizes |
Возвращает размеры ключа (в битах), которые поддерживаются симметричным алгоритмом.Gets the key sizes, in bits, that are supported by the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
Mode |
Возвращает или задает режим функционирования симметричного алгоритма.Gets or sets the mode for operation of the symmetric algorithm. |
Mode |
Возвращает или задает режим функционирования симметричного алгоритма.Gets or sets the mode for operation of the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
Padding |
Возвращает или задает режим заполнения, используемый в симметричном алгоритме.Gets or sets the padding mode used in the symmetric algorithm. |
Padding |
Возвращает или задает режим заполнения, используемый в симметричном алгоритме.Gets or sets the padding mode used in the symmetric algorithm. (Унаследовано от SymmetricAlgorithm) |
Методы
Clear() |
Освобождает все ресурсы, используемые классом SymmetricAlgorithm.Releases all resources used by the SymmetricAlgorithm class. (Унаследовано от SymmetricAlgorithm) |
CreateDecryptor() |
Создает симметричный объект-дешифратор с текущим свойством Key и вектором инициализации (IV).Creates a symmetric decryptor object with the current Key property and initialization vector (IV). |
CreateDecryptor() |
Создает симметричный объект-дешифратор с текущим свойством Key и вектором инициализации (IV).Creates a symmetric decryptor object with the current Key property and initialization vector (IV). (Унаследовано от SymmetricAlgorithm) |
CreateDecryptor(Byte[], Byte[]) |
Создает объект-дешифратор Rijndael для алгоритма симметричного шифрования с заданным ключом (Key) и вектором инициализации (IV).Creates a symmetric Rijndael decryptor object with the specified Key and initialization vector (IV). |
CreateEncryptor() |
Создает симметричный объект-шифратор с текущим свойством Key и вектором инициализации (IV).Creates a symmetric encryptor object with the current Key property and initialization vector (IV). |
CreateEncryptor() |
Создает симметричный объект-шифратор с текущим свойством Key и вектором инициализации (IV).Creates a symmetric encryptor object with the current Key property and initialization vector (IV). (Унаследовано от SymmetricAlgorithm) |
CreateEncryptor(Byte[], Byte[]) |
Создает объект-шифратор Rijndael для алгоритма симметричного шифрования с заданным ключом (Key) и вектором инициализации (IV).Creates a symmetric Rijndael encryptor object with the specified Key and initialization vector (IV). |
Dispose() |
Освобождает все ресурсы, используемые текущим экземпляром класса SymmetricAlgorithm.Releases all resources used by the current instance of the SymmetricAlgorithm class. (Унаследовано от SymmetricAlgorithm) |
Dispose(Boolean) |
Освобождает неуправляемые ресурсы, используемые объектом SymmetricAlgorithm, а при необходимости освобождает также управляемые ресурсы.Releases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources. (Унаследовано от SymmetricAlgorithm) |
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object. (Унаследовано от Object) |
GenerateIV() |
Генерирует случайный вектор инициализации (IV) для использования данным алгоритмом.Generates a random initialization vector (IV) to be used for the algorithm. |
GenerateKey() |
Генерирует случайный ключ (Key) для использования данным алгоритмом.Generates a random Key to be used for the algorithm. |
GetHashCode() |
Служит хэш-функцией по умолчанию.Serves as the default hash function. (Унаследовано от Object) |
GetType() |
Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance. (Унаследовано от Object) |
MemberwiseClone() |
Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object. (Унаследовано от Object) |
ToString() |
Возвращает строку, представляющую текущий объект.Returns a string that represents the current object. (Унаследовано от Object) |
ValidKeySize(Int32) |
Определяет, является ли заданный размер ключа допустимым для текущего алгоритма.Determines whether the specified key size is valid for the current algorithm. (Унаследовано от SymmetricAlgorithm) |
Явные реализации интерфейса
IDisposable.Dispose() |
Этот API поддерживает инфраструктуру продукта и не предназначен для использования непосредственно из программного кода. Освобождает неуправляемые ресурсы, используемые объектом SymmetricAlgorithm, а при необходимости освобождает также управляемые ресурсы.Releases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources. (Унаследовано от SymmetricAlgorithm) |