RijndaelManaged Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Обращается к управляемой версии алгоритма Rijndael . Этот класс не наследуется.
public ref class RijndaelManaged sealed : 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
type RijndaelManaged = class
inherit Rijndael
[<System.Runtime.InteropServices.ComVisible(true)>]
type RijndaelManaged = class
inherit Rijndael
Public NotInheritable Class RijndaelManaged
Inherits Rijndael
- Наследование
- Атрибуты
Примеры
В следующем примере показано, как шифровать и расшифровывать примеры данных с помощью RijndaelManaged класса.
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 битов. В .NET Framework этот алгоритм поддерживает размеры блоков размером 128, 192 или 256 бит; по умолчанию — 128 бит (Aes-совместимые). В .NET Core он совпадает с AES и поддерживает только 128-разрядный размер блока.
Important
Класс Rijndael является предшественником алгоритма Aes . Вместо этого следует использовать Aes алгоритм Rijndael. Дополнительные сведения см. в записи Различия между Rijndael и AES в блоге по безопасности .NET.
Конструкторы
| Имя | Описание |
|---|---|
| RijndaelManaged() |
Инициализирует новый экземпляр класса RijndaelManaged. |
Поля
| Имя | Описание |
|---|---|
| BlockSizeValue |
Представляет размер блока в битах криптографической операции. (Унаследовано от SymmetricAlgorithm) |
| FeedbackSizeValue |
Представляет размер обратной связи (в битах) криптографической операции. (Унаследовано от SymmetricAlgorithm) |
| IVValue |
Представляет вектор инициализации (IV) для симметричного алгоритма. (Унаследовано от SymmetricAlgorithm) |
| KeySizeValue |
Представляет размер в битах секретного ключа, используемого симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| KeyValue |
Представляет секретный ключ для симметричного алгоритма. (Унаследовано от SymmetricAlgorithm) |
| LegalBlockSizesValue |
Указывает размеры блоков в битах, поддерживаемые симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| LegalKeySizesValue |
Указывает размеры ключей в битах, поддерживаемые симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| ModeValue |
Представляет режим шифра, используемый в симметричном алгоритме. (Унаследовано от SymmetricAlgorithm) |
| PaddingValue |
Представляет режим заполнения, используемый в симметричном алгоритме. (Унаследовано от SymmetricAlgorithm) |
Свойства
| Имя | Описание |
|---|---|
| BlockSize |
Возвращает или задает размер блока в битах криптографической операции. |
| BlockSize |
Возвращает или задает размер блока в битах криптографической операции. (Унаследовано от SymmetricAlgorithm) |
| FeedbackSize |
Возвращает или задает размер обратной связи (в битах) криптографической операции для режимов шифрования обратной связи (CFB) и выходных отзывов (OFB). (Унаследовано от SymmetricAlgorithm) |
| IV |
Получает или задает вектор инициализации (IV), используемый для симметричного алгоритма. |
| IV |
Возвращает или задает вектор инициализации (IV) для симметричного алгоритма. (Унаследовано от SymmetricAlgorithm) |
| Key |
Возвращает или задает секретный ключ, используемый для симметричного алгоритма. |
| Key |
Возвращает или задает секретный ключ для симметричного алгоритма. (Унаследовано от SymmetricAlgorithm) |
| KeySize |
Возвращает или задает размер в битах секретного ключа, используемого для симметричного алгоритма. |
| KeySize |
Возвращает или задает размер в битах секретного ключа, используемого симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| LegalBlockSizes |
Возвращает размеры блоков в битах, поддерживаемые симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| LegalKeySizes |
Возвращает размеры ключей в битах, поддерживаемые симметричным алгоритмом. |
| LegalKeySizes |
Возвращает размеры ключей в битах, поддерживаемые симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| Mode |
Возвращает или задает режим для работы симметричного алгоритма. |
| Mode |
Возвращает или задает режим для работы симметричного алгоритма. (Унаследовано от SymmetricAlgorithm) |
| Padding |
Возвращает или задает режим заполнения, используемый в симметричном алгоритме. |
| Padding |
Возвращает или задает режим заполнения, используемый в симметричном алгоритме. (Унаследовано от SymmetricAlgorithm) |
Методы
| Имя | Описание |
|---|---|
| Clear() |
Освобождает все ресурсы, используемые классом SymmetricAlgorithm . (Унаследовано от SymmetricAlgorithm) |
| CreateDecryptor() |
Создает объект симметричного расшифровки с текущим Key свойством и вектором инициализации (IV). |
| CreateDecryptor() |
Создает объект симметричного расшифровки с текущим Key свойством и вектором инициализации (IV). (Унаследовано от SymmetricAlgorithm) |
| CreateDecryptor(Byte[], Byte[]) |
Создает объект симметричного Rijndael расшифровчика с указанным Key и инициализационным вектором (IV). |
| CreateEncryptor() |
Создает объект симметричного шифратора с текущим Key свойством и вектором инициализации (IV). |
| CreateEncryptor() |
Создает объект симметричного шифратора с текущим Key свойством и вектором инициализации (IV). (Унаследовано от SymmetricAlgorithm) |
| CreateEncryptor(Byte[], Byte[]) |
Создает объект симметричного Rijndael шифрования с указанным Key и инициализационным вектором (IV). |
| Dispose() |
Освобождает все ресурсы, используемые текущим экземпляром класса SymmetricAlgorithm. (Унаследовано от SymmetricAlgorithm) |
| Dispose(Boolean) |
Освобождает неуправляемые ресурсы, используемые SymmetricAlgorithm и при необходимости освобождает управляемые ресурсы. (Унаследовано от SymmetricAlgorithm) |
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GenerateIV() |
Создает вектор случайной инициализации (IV), используемый для алгоритма. |
| GenerateKey() |
Создает случайное Key использование алгоритма. |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
| ValidKeySize(Int32) |
Определяет, является ли указанный размер ключа допустимым для текущего алгоритма. (Унаследовано от SymmetricAlgorithm) |
Явные реализации интерфейса
| Имя | Описание |
|---|---|
| IDisposable.Dispose() |
Этот API поддерживает инфраструктуру продукта и не предназначен для использования непосредственно из программного кода. Освобождает неуправляемые ресурсы, используемые SymmetricAlgorithm и при необходимости освобождает управляемые ресурсы. (Унаследовано от SymmetricAlgorithm) |