CryptographicEngine.Encrypt(CryptographicKey, IBuffer, IBuffer) 方法

定义

使用对称或非对称算法加密数据。

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

参数

key
CryptographicKey

用于加密的加密密钥。 这可以是非对称密钥,也可以是对称密钥。 有关详细信息,请参阅 AsymmetricKeyAlgorithmProviderSymmetricKeyAlgorithmProvider

data
IBuffer

要加密的数据。

iv
IBuffer

包含初始化向量的缓冲区。 对于对称算法,这可以为 null ,对于非对称算法,应始终为 null 。 如果使用初始化向量 (IV) 来加密数据,则必须使用相同的 IV 来解密数据。 可以使用 GenerateRandom 方法创建包含随机数据的 IV。 其他 IV(如非ce 生成的向量)需要自定义实现。 有关详细信息,请参阅 加密密钥

加密块链接 (CBC) 块密码模式算法需要初始化向量。 有关详细信息,请参阅“备注”。

返回

已加密的数据。

示例

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;
}

注解

在 Microsoft 支持的对称算法中,以下算法需要初始化向量:

适用于

另请参阅