RSACryptoServiceProvider.Encrypt Método

Definición

Cifra los datos con el algoritmo RSA.Encrypts data with the RSA algorithm.

Sobrecargas

Encrypt(Byte[], Boolean)

Cifra los datos con el algoritmo RSA.Encrypts data with the RSA algorithm.

Encrypt(Byte[], RSAEncryptionPadding)

Cifra los datos con el algoritmo RSA utilizando el relleno especificado.Encrypts data with the RSA algorithm using the specified padding.

Encrypt(Byte[], Boolean)

Cifra los datos con el algoritmo RSA.Encrypts data with the RSA algorithm.

public:
 cli::array <System::Byte> ^ Encrypt(cli::array <System::Byte> ^ rgb, bool fOAEP);
public byte[] Encrypt (byte[] rgb, bool fOAEP);
override this.Encrypt : byte[] * bool -> byte[]
member this.Encrypt : byte[] * bool -> byte[]
Public Function Encrypt (rgb As Byte(), fOAEP As Boolean) As Byte()

Parámetros

rgb
Byte[]

Datos que se van a cifrar.The data to be encrypted.

fOAEP
Boolean

true para realizar el cifrado RSA directo mediante el relleno de OAEP (solo disponible en equipos con Windows XP o versiones posteriores); de lo contrario, false para usar el relleno PKCS#1 v1.5.true to perform direct RSA encryption using OAEP padding (only available on a computer running Windows XP or later); otherwise, false to use PKCS#1 v1.5 padding.

Devoluciones

Byte[]

Datos cifrados.The encrypted data.

Excepciones

No se puede adquirir el proveedor de servicios criptográficos (CSP).The cryptographic service provider (CSP) cannot be acquired.

o bien-or- La longitud del parámetro rgb es mayor que la longitud máxima permitida.The length of the rgb parameter is greater than the maximum allowed length.

rgb es null.rgb is null.

Ejemplos

En el ejemplo de código siguiente se inicializa un RSACryptoServiceProvider objeto con el valor de una clave pública (enviada por otra entidad), se genera una clave de sesión mediante el Aes algoritmo y, a continuación, se cifra la clave de sesión mediante el RSACryptoServiceProvider objeto.The following code example initializes an RSACryptoServiceProvider object to the value of a public key (sent by another party), generates a session key using the Aes algorithm, and then encrypts the session key using the RSACryptoServiceProvider object. Con este esquema, la clave de sesión podría enviarse de vuelta al propietario de la clave RSA privada y las dos partes podrían usar la clave de sesión para intercambiar los datos cifrados.Using this scheme, the session key could be sent back to the owner of the private RSA key and the two parties could use the session key to exchange encrypted data.

#using <System.dll>

using namespace System;
using namespace System::Security::Cryptography;
int main()
{
   try
   {
      
      //initialze the Byte arrays to the public key information.
      array<Byte>^PublicKey = {214,46,220,83,160,73,40,39,201,155,19,202,3,11,191,178,56,74,90,36,248,103,18,144,170,163,145,87,54,61,34,220,222,207,137,149,173,14,92,120,206,222,158,28,40,24,30,16,175,108,128,35,230,118,40,121,113,125,216,130,11,24,90,48,194,240,105,44,76,34,57,249,228,125,80,38,9,136,29,117,207,139,168,181,85,137,126,10,126,242,120,247,121,8,100,12,201,171,38,226,193,180,190,117,177,87,143,242,213,11,44,180,113,93,106,99,179,68,175,211,164,116,64,148,226,254,172,147};
      array<Byte>^Exponent = {1,0,1};
      
      //Values to store encrypted symmetric keys.
      array<Byte>^EncryptedSymmetricKey;
      array<Byte>^EncryptedSymmetricIV;
      
      //Create a new instance of RSACryptoServiceProvider.
      RSACryptoServiceProvider^ RSA = gcnew RSACryptoServiceProvider;
      
      //Create a new instance of RSAParameters.
      RSAParameters RSAKeyInfo;
      
      //Set RSAKeyInfo to the public key values. 
      RSAKeyInfo.Modulus = PublicKey;
      RSAKeyInfo.Exponent = Exponent;
      
      //Import key parameters into RSA.
      RSA->ImportParameters( RSAKeyInfo );
      
      //Create a new instance of the Aes class.
      Aes^ aes = Aes::Create();
      
      //Encrypt the symmetric key and IV.
      EncryptedSymmetricKey = RSA->Encrypt( aes->Key, false );
      EncryptedSymmetricIV = RSA->Encrypt( aes->IV, false );
      Console::WriteLine( "Aes Key and IV have been encrypted with RSACryptoServiceProvider." );
   }
   catch ( CryptographicException^ e ) 
   {
      
      //Catch and display a CryptographicException  
      //to the console.
      Console::WriteLine( e->Message );
   }

}

using System;
using System.Security.Cryptography;

class RSACSPSample
{

    static void Main()
    {
        try
        {		//initialze the byte arrays to the public key information.
            byte[] PublicKey = {214,46,220,83,160,73,40,39,201,155,19,202,3,11,191,178,56,
                                   74,90,36,248,103,18,144,170,163,145,87,54,61,34,220,222,
                                   207,137,149,173,14,92,120,206,222,158,28,40,24,30,16,175,
                                   108,128,35,230,118,40,121,113,125,216,130,11,24,90,48,194,
                                   240,105,44,76,34,57,249,228,125,80,38,9,136,29,117,207,139,
                                   168,181,85,137,126,10,126,242,120,247,121,8,100,12,201,171,
                                   38,226,193,180,190,117,177,87,143,242,213,11,44,180,113,93,
                                   106,99,179,68,175,211,164,116,64,148,226,254,172,147};

            byte[] Exponent = {1,0,1};
      
            //Values to store encrypted symmetric keys.
            byte[] EncryptedSymmetricKey;
            byte[] EncryptedSymmetricIV;

            //Create a new instance of RSACryptoServiceProvider.
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

            //Create a new instance of RSAParameters.
            RSAParameters RSAKeyInfo = new RSAParameters();

            //Set RSAKeyInfo to the public key values. 
            RSAKeyInfo.Modulus = PublicKey;
            RSAKeyInfo.Exponent = Exponent;

            //Import key parameters into RSA.
            RSA.ImportParameters(RSAKeyInfo);

            //Create a new instance of the Aes class.
            Aes aes = Aes.Create();

            //Encrypt the symmetric key and IV.
            EncryptedSymmetricKey = RSA.Encrypt(aes.Key, false);
            EncryptedSymmetricIV = RSA.Encrypt(aes.IV, false);

            Console.WriteLine("Aes Key and IV have been encrypted with RSACryptoServiceProvider."); 
        }
        //Catch and display a CryptographicException  
        //to the console.
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
Imports System.Security.Cryptography

Class RSACSPSample

    Shared Sub Main()
        Try
            'initialze the byte arrays to the public key information.
            Dim PublicKey As Byte() = {214, 46, 220, 83, 160, 73, 40, 39, 201, 155, 19, 202, 3, 11, 191, 178, 56, 74, 90, 36, 248, 103, 18, 144, 170, 163, 145, 87, 54, 61, 34, 220, 222, 207, 137, 149, 173, 14, 92, 120, 206, 222, 158, 28, 40, 24, 30, 16, 175, 108, 128, 35, 230, 118, 40, 121, 113, 125, 216, 130, 11, 24, 90, 48, 194, 240, 105, 44, 76, 34, 57, 249, 228, 125, 80, 38, 9, 136, 29, 117, 207, 139, 168, 181, 85, 137, 126, 10, 126, 242, 120, 247, 121, 8, 100, 12, 201, 171, 38, 226, 193, 180, 190, 117, 177, 87, 143, 242, 213, 11, 44, 180, 113, 93, 106, 99, 179, 68, 175, 211, 164, 116, 64, 148, 226, 254, 172, 147}

            Dim Exponent As Byte() = {1, 0, 1}

            'Values to store encrypted symmetric keys.
            Dim EncryptedSymmetricKey() As Byte
            Dim EncryptedSymmetricIV() As Byte

            'Create a new instance of RSACryptoServiceProvider.
            Dim RSA As New RSACryptoServiceProvider()

            'Create a new instance of RSAParameters.
            Dim RSAKeyInfo As New RSAParameters()

            'Set RSAKeyInfo to the public key values. 
            RSAKeyInfo.Modulus = PublicKey
            RSAKeyInfo.Exponent = Exponent

            'Import key parameters into RSA.
            RSA.ImportParameters(RSAKeyInfo)

            'Create a new instance of the Aes class.
            Dim aes As Aes = Aes.Create()

            'Encrypt the symmetric key and IV.
            EncryptedSymmetricKey = RSA.Encrypt(aes.Key, False)
            EncryptedSymmetricIV = RSA.Encrypt(aes.IV, False)

            Console.WriteLine("Aes Key and IV have been encrypted with RSA.")

            'Catch and display a CryptographicException  
            'to the console.
        Catch e As CryptographicException
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Class

Comentarios

En la tabla siguiente se describe el relleno que admiten las diferentes versiones de Microsoft Windows y la longitud máxima rgb permitida por las diferentes combinaciones de sistemas operativos y relleno.The following table describes the padding supported by different versions of Microsoft Windows and the maximum length of rgb allowed by the different combinations of operating systems and padding.

RellenoPadding Longitud máxima del parámetro RGBMaximum Length of rgb Parameter
Relleno OAEP (PKCS # 1 V2)OAEP padding (PKCS#1 v2) Tamaño de módulo: 2-2 * hLen, donde hLen es el tamaño del hash.Modulus size -2 -2*hLen, where hLen is the size of the hash.
Cifrado directo (PKCS # 1 v 1.5)Direct Encryption (PKCS#1 v1.5) Tamaño de módulo: 11.Modulus size - 11. (11 bytes es el relleno mínimo posible).(11 bytes is the minimum padding possible.)

Utilice Decrypt para descifrar los resultados de este método.Use Decrypt to decrypt the results of this method.

Consulte también

Se aplica a

Encrypt(Byte[], RSAEncryptionPadding)

Cifra los datos con el algoritmo RSA utilizando el relleno especificado.Encrypts data with the RSA algorithm using the specified padding.

public:
 override cli::array <System::Byte> ^ Encrypt(cli::array <System::Byte> ^ data, System::Security::Cryptography::RSAEncryptionPadding ^ padding);
public override byte[] Encrypt (byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding);
override this.Encrypt : byte[] * System.Security.Cryptography.RSAEncryptionPadding -> byte[]
Public Overrides Function Encrypt (data As Byte(), padding As RSAEncryptionPadding) As Byte()

Parámetros

data
Byte[]

Datos que se van a cifrar.The data to encrypt.

padding
RSAEncryptionPadding

Relleno.The padding.

Devoluciones

Byte[]

Datos cifrados.The encrypted data.

Excepciones

data es null.data is null.

o bien-or- padding es null.padding is null.

No se admite el modo de relleno.The padding mode is not supported.

Comentarios

padding debe ser RSAEncryptionPadding.Pkcs1 o RSAEncryptionPadding.OaepSHA1 .padding must be either RSAEncryptionPadding.Pkcs1 or RSAEncryptionPadding.OaepSHA1.

Se aplica a