英語で読む

次の方法で共有


DataProtectionScope 列挙型

定義

Protect(Byte[], Byte[], DataProtectionScope) メソッドによって適用されるデータ保護のスコープを指定します。

C#
public enum DataProtectionScope
継承
DataProtectionScope

フィールド

名前 説明
CurrentUser 0

保護されたデータは、現在のユーザーに関連付けられます。 現在のユーザー コンテキスト下で実行されているスレッドだけがデータの保護を解除できます。

LocalMachine 1

保護されたデータは、コンピューターのコンテキストに関連付けられます。 コンピューター上で実行されているすべてのプロセスがデータの保護を解除できます。 この列挙値は、サーバーに固有のアプリケーション (つまり、信頼のおけるユーザー以外はアクセスできないサーバー上で動作するアプリケーション) で使用されます。

次のコード例は、データ保護の使用方法を示しています。

C#
using System;
using System.Security.Cryptography;

public class DataProtectionSample
{
    // Create byte array for additional entropy when using Protect method.
    static byte [] s_additionalEntropy = { 9, 8, 7, 6, 5 };

    public static void Main()
    {
        // Create a simple byte array containing data to be encrypted.
        byte [] secret = { 0, 1, 2, 3, 4, 1, 2, 3, 4 };

        //Encrypt the data.
        byte [] encryptedSecret = Protect( secret );
        Console.WriteLine("The encrypted byte array is:");
        PrintValues(encryptedSecret);

        // Decrypt the data and store in a byte array.
        byte [] originalData = Unprotect( encryptedSecret );
        Console.WriteLine("{0}The original data is:", Environment.NewLine);
        PrintValues(originalData);
    }

    public static byte [] Protect( byte [] data )
    {
        try
        {
            // Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted
            // only by the same current user.
            return ProtectedData.Protect( data, s_additionalEntropy, DataProtectionScope.CurrentUser );
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not encrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

    public static byte [] Unprotect( byte [] data )
    {
        try
        {
            //Decrypt the data using DataProtectionScope.CurrentUser.
            return ProtectedData.Unprotect( data, s_additionalEntropy, DataProtectionScope.CurrentUser );
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not decrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

    public static void PrintValues( Byte[] myArr )
    {
        foreach ( Byte i in myArr )
        {
            Console.Write( "\t{0}", i );
        }
        Console.WriteLine();
    }
}

注釈

この列挙は、 メソッドおよび Unprotect メソッドと共Protectに使用され、暗号化によってデータを保護します。

注意 LocalMachine 列挙値を使用すると、複数のアカウントでデータの保護を解除できます。 この値は、コンピューター上のすべてのアカウントを信頼する場合にのみ使用します。 ほとんどの場合、CurrentUser 値を使用する必要があります。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, 8 (package-provided), 9 (package-provided), 10 (package-provided)
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10