Share via


CryptographicEngine.Encrypt(CryptographicKey, IBuffer, IBuffer) Método

Definição

Criptografa dados usando um algoritmo simétrico ou assimétrico.

public:
 static IBuffer ^ Encrypt(CryptographicKey ^ key, IBuffer ^ data, IBuffer ^ iv);
 static IBuffer Encrypt(CryptographicKey const& key, IBuffer const& data, IBuffer const& iv);
public static IBuffer Encrypt(CryptographicKey key, IBuffer data, IBuffer iv);
function encrypt(key, data, iv)
Public Shared Function Encrypt (key As CryptographicKey, data As IBuffer, iv As IBuffer) As IBuffer

Parâmetros

key
CryptographicKey

Chave criptográfica a ser usada para criptografia. Isso pode ser uma chave assimétrica ou simétrica. Para obter mais informações, consulte AsymmetricKeyAlgorithmProvider e SymmetricKeyAlgorithmProvider.

data
IBuffer

Dados a serem criptografados.

iv
IBuffer

Buffer que contém o vetor de inicialização. Isso pode ser nulo para um algoritmo simétrico e sempre deve ser nulo para um algoritmo assimétrico. Se um iv (vetor de inicialização) foi usado para criptografar os dados, você deve usar o mesmo IV para descriptografar os dados. Você pode usar o método GenerateRandom para criar um IV que contenha dados aleatórios. Outras IVs, como vetores gerados por nonce, exigem implementação personalizada. Para obter mais informações, consulte Chaves criptográficas.

Os algoritmos de modo de criptografia de bloco cbc (encadeamento de criptografia) exigem um vetor de inicialização. Para obter mais informações, consulte Comentários.

Retornos

Dados criptografados.

Exemplos

public IBuffer SampleCipherEncryption(
    String strMsg,
    String strAlgName,
    UInt32 keyLength,
    out BinaryStringEncoding encoding,
    out IBuffer iv,
    out CryptographicKey key)
{
    // Initialize the initialization vector.
    iv = null;

    // Initialize the binary encoding value.
    encoding = BinaryStringEncoding.Utf8;

    // Create a buffer that contains the encoded message to be encrypted. 
    IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

    // Open a symmetric algorithm provider for the specified algorithm. 
    SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);

    // Determine whether the message length is a multiple of the block length.
    // This is not necessary for PKCS #7 algorithms which automatically pad the
    // message to an appropriate length.
    if (!strAlgName.Contains("PKCS7"))
    {
        if ((buffMsg.Length % objAlg.BlockLength) != 0)
        {
            throw new Exception("Message buffer length must be multiple of block length.");
        }
    }

    // Create a symmetric key.
    IBuffer keyMaterial = CryptographicBuffer.GenerateRandom(keyLength);
    key = objAlg.CreateSymmetricKey(keyMaterial);

    // CBC algorithms require an initialization vector. Here, a random
    // number is used for the vector.
    if (strAlgName.Contains("CBC"))
    {
        iv = CryptographicBuffer.GenerateRandom(objAlg.BlockLength);
    }

    // Encrypt the data and return.
    IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, buffMsg, iv);
    return buffEncrypt;
}

Comentários

Dos algoritmos simétricos compatíveis com a Microsoft, o seguinte requer um vetor de inicialização:

Aplica-se a

Confira também