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,例如非產生的向量,需要自訂實作。 如需詳細資訊,請參閱 密碼編譯金鑰

加密區塊鏈結 (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 支援的對稱演算法中,下列專案需要初始化向量:

適用於

另請參閱