RijndaelManaged Classe

Définition

Accède à la version managée de l’algorithme Rijndael . Cette classe ne peut pas être héritée.

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
Héritage
Attributs

Exemples

L’exemple suivant montre comment chiffrer et déchiffrer des exemples de données à l’aide de la RijndaelManaged classe.

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

Remarques

Cet algorithme prend en charge les longueurs de clé de 128, 192 ou 256 bits ; valeur par défaut de 256 bits. Dans .NET Framework, cet algorithme prend en charge les tailles de bloc de 128, 192 ou 256 bits ; la valeur par défaut est de 128 bits (Aes compatible). Dans .NET Core, il est identique à AES et ne prend en charge qu’une taille de bloc 128 bits.

Important

La Rijndael classe est le prédécesseur de l’algorithme Aes . Vous devez utiliser l’algorithme Aes au lieu de Rijndael. Pour plus d’informations, consultez l’entrée The Differences Between Rijndael and AES dans le blog .NET Security.

Constructeurs

Nom Description
RijndaelManaged()

Initialise une nouvelle instance de la classe RijndaelManaged.

Champs

Nom Description
BlockSizeValue

Représente la taille de bloc, en bits, de l’opération de chiffrement.

(Hérité de SymmetricAlgorithm)
FeedbackSizeValue

Représente la taille de commentaires, en bits, de l’opération de chiffrement.

(Hérité de SymmetricAlgorithm)
IVValue

Représente le vecteur d’initialisation (IV) pour l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
KeySizeValue

Représente la taille, en bits, de la clé secrète utilisée par l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
KeyValue

Représente la clé secrète de l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
LegalBlockSizesValue

Spécifie les tailles de bloc, en bits, prises en charge par l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
LegalKeySizesValue

Spécifie les tailles de clé, en bits, prises en charge par l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
ModeValue

Représente le mode de chiffrement utilisé dans l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
PaddingValue

Représente le mode de remplissage utilisé dans l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)

Propriétés

Nom Description
BlockSize

Obtient ou définit la taille de bloc, en bits, de l’opération de chiffrement.

BlockSize

Obtient ou définit la taille de bloc, en bits, de l’opération de chiffrement.

(Hérité de SymmetricAlgorithm)
FeedbackSize

Obtient ou définit la taille des commentaires, en bits, de l’opération de chiffrement pour les modes de chiffrement de commentaires de chiffrement (CFB) et de retour de sortie (OFB).

(Hérité de SymmetricAlgorithm)
IV

Obtient ou définit le vecteur d’initialisation (IV) à utiliser pour l’algorithme symétrique.

IV

Obtient ou définit le vecteur d’initialisation (IV) pour l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
Key

Obtient ou définit la clé secrète utilisée pour l’algorithme symétrique.

Key

Obtient ou définit la clé secrète de l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
KeySize

Obtient ou définit la taille, en bits, de la clé secrète utilisée pour l’algorithme symétrique.

KeySize

Obtient ou définit la taille, en bits, de la clé secrète utilisée par l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
LegalBlockSizes

Obtient les tailles de bloc, en bits, prises en charge par l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
LegalKeySizes

Obtient les tailles de clé, en bits, prises en charge par l’algorithme symétrique.

LegalKeySizes

Obtient les tailles de clé, en bits, prises en charge par l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
Mode

Obtient ou définit le mode pour l’opération de l’algorithme symétrique.

Mode

Obtient ou définit le mode pour l’opération de l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)
Padding

Obtient ou définit le mode de remplissage utilisé dans l’algorithme symétrique.

Padding

Obtient ou définit le mode de remplissage utilisé dans l’algorithme symétrique.

(Hérité de SymmetricAlgorithm)

Méthodes

Nom Description
Clear()

Libère toutes les ressources utilisées par la SymmetricAlgorithm classe.

(Hérité de SymmetricAlgorithm)
CreateDecryptor()

Crée un objet de déchiffreur symétrique avec la propriété actuelle Key et le vecteur d’initialisation (IV).

CreateDecryptor()

Crée un objet de déchiffreur symétrique avec la propriété actuelle Key et le vecteur d’initialisation (IV).

(Hérité de SymmetricAlgorithm)
CreateDecryptor(Byte[], Byte[])

Crée un objet de déchiffreur symétrique Rijndael avec le vecteur d’initialisation et spécifié Key (IV).

CreateEncryptor()

Crée un objet encrypteur symétrique avec la propriété actuelle Key et le vecteur d’initialisation (IV).

CreateEncryptor()

Crée un objet encrypteur symétrique avec la propriété actuelle Key et le vecteur d’initialisation (IV).

(Hérité de SymmetricAlgorithm)
CreateEncryptor(Byte[], Byte[])

Crée un objet encrypteur symétrique Rijndael avec le vecteur d’initialisation et spécifié Key (IV).

Dispose()

Libère toutes les ressources utilisées par l’instance actuelle de la SymmetricAlgorithm classe.

(Hérité de SymmetricAlgorithm)
Dispose(Boolean)

Libère les ressources non managées utilisées par les SymmetricAlgorithm ressources gérées et libère éventuellement les ressources managées.

(Hérité de SymmetricAlgorithm)
Equals(Object)

Détermine si l’objet spécifié est égal à l’objet actuel.

(Hérité de Object)
GenerateIV()

Génère un vecteur d’initialisation aléatoire (IV) à utiliser pour l’algorithme.

GenerateKey()

Génère un hasard Key à utiliser pour l’algorithme.

GetHashCode()

Sert de fonction de hachage par défaut.

(Hérité de Object)
GetType()

Obtient la Type de l’instance actuelle.

(Hérité de Object)
MemberwiseClone()

Crée une copie superficielle du Objectactuel.

(Hérité de Object)
ToString()

Retourne une chaîne qui représente l’objet actuel.

(Hérité de Object)
ValidKeySize(Int32)

Détermine si la taille de clé spécifiée est valide pour l’algorithme actuel.

(Hérité de SymmetricAlgorithm)

Implémentations d’interfaces explicites

Nom Description
IDisposable.Dispose()

Cette API prend en charge l'infrastructure du produit et n'est pas destinée à être utilisée directement à partir de votre code.

Libère les ressources non managées utilisées par les SymmetricAlgorithm ressources gérées et libère éventuellement les ressources managées.

(Hérité de SymmetricAlgorithm)

S’applique à

Voir aussi