Language
対称暗号化と非対称暗号化は、異なるプロセスを使用して実行されます。 対称暗号化はストリームで実行されるため、大量のデータを暗号化する場合に便利です。 非対称暗号化は少数のバイトで実行されるため、少量のデータに対してのみ役立ちます。
対称暗号化
Important
Aes.Create()メソッドは、既定では、組み込みの認証なしで CBC モードになります。 整合性検証を行わない CBC モードは、パディングオラクル攻撃に対して脆弱です。 運用環境のシナリオでは、暗号化解除の前にデータの整合性を確認します。たとえば、Encrypt-then-MAC パターンを適用します。 詳細については、「パディングを 使用した CBC モードの対称復号によるタイミングの脆弱性」を参照してください。
マネージド対称暗号化クラスは、ストリームに読み取られたデータを暗号化する CryptoStream と呼ばれる特殊なストリーム クラスと共に使用されます。 CryptoStream クラスは、マネージド ストリーム クラス、(暗号化アルゴリズムを実装するクラスから作成された) ICryptoTransform インターフェイスを実装するクラス、および CryptoStreamMode に許可されるアクセスの種類を記述する 列挙体で初期化されます。 CryptoStream クラスは、FileStream、MemoryStream、NetworkStreamなど、Stream クラスから派生する任意のクラスを使用して初期化できます。 これらのクラスを使用すると、さまざまなストリーム オブジェクトに対して対称暗号化を実行できます。
次の例は、 Aes アルゴリズムの既定の実装クラスの新しいインスタンスを作成する方法を示しています。 このインスタンスが、CryptoStream クラスに対して暗号化を実行するために使用されます。 この例では、 CryptoStream は、任意の種類のマネージド ストリームにすることができる fileStream というストリーム オブジェクトで初期化されます。
Aes クラスの CreateEncryptor メソッドには、暗号化に使用されるキーと IV が渡されます。 この場合、 aes から生成された既定のキーと IV が使用されます。
Dim aes As Aes = Aes.Create()
Dim cryptStream As New CryptoStream(
fileStream, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write)
Aes aes = Aes.Create();
CryptoStream cryptStream = new CryptoStream(
fileStream, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write);
このコードが実行されると、 CryptoStream オブジェクトに書き込まれたデータはすべて、AES アルゴリズムを使用して暗号化されます。
次の例は、ストリームの作成、ストリームの暗号化、ストリームへの書き込み、ストリームの終了のプロセス全体を示しています。 この例では、 CryptoStream クラスと Aes クラスを使用して暗号化されたファイル ストリームを作成します。 生成された IV は FileStreamの先頭に書き込まれるので、読み取って復号化に使用できます。 その後、 StreamWriter クラスを使用して、暗号化されたストリームにメッセージが書き込まれます。 同じキーを複数回使用してデータの暗号化と復号化を行うことができますが、毎回新しいランダム IV を生成することをお勧めします。 このように、プレーン テキストが同じ場合でも、暗号化されたデータは常に異なります。
using System.Security.Cryptography;
try
{
using (FileStream fileStream = new("TestData.txt", FileMode.OpenOrCreate))
{
using (Aes aes = Aes.Create())
{
// This key is for illustration purposes only.
// In production, use a securely stored or managed key.
byte[] key =
{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16
};
aes.Key = key;
byte[] iv = aes.IV;
fileStream.Write(iv, 0, iv.Length);
using (CryptoStream cryptoStream = new(
fileStream,
aes.CreateEncryptor(),
CryptoStreamMode.Write))
{
// By default, the StreamWriter uses UTF-8 encoding.
// To change the text encoding, pass the desired encoding as the second parameter.
// For example, new StreamWriter(cryptoStream, Encoding.Unicode).
using (StreamWriter encryptWriter = new(cryptoStream))
{
encryptWriter.WriteLine("Hello World!");
}
}
}
}
Console.WriteLine("The file was encrypted.");
}
catch (Exception ex)
{
Console.WriteLine($"The encryption failed. {ex}");
}
Imports System
Imports System.IO
Imports System.Security.Cryptography
Module Module1
Sub Main()
Try
' Create a file stream
Using fileStream As New FileStream("TestData.txt", FileMode.OpenOrCreate)
' Create a new instance of the default Aes implementation class
' and configure encryption key.
Using aes As Aes = Aes.Create()
' This key is for illustration purposes only.
' In production, use a securely stored or managed key.
Dim key As Byte() = {
&H1, &H2, &H3, &H4, &H5, &H6, &H7, &H8,
&H9, &H10, &H11, &H12, &H13, &H14, &H15, &H16
}
aes.Key = key
' Stores IV at the beginning of the file.
' This information will be used for decryption.
Dim iv As Byte() = aes.IV
fileStream.Write(iv, 0, iv.Length)
' Create a CryptoStream, pass it the FileStream, and encrypt
' it with the Aes class.
Using cryptoStream As New CryptoStream(fileStream, aes.CreateEncryptor(), CryptoStreamMode.Write)
' By default, the StreamWriter uses UTF-8 encoding.
' To change the text encoding, pass the desired encoding as the second parameter.
' For example, New StreamWriter(cryptoStream, Encoding.Unicode).
Using sWriter As New StreamWriter(cryptoStream)
'Write to the stream.
sWriter.WriteLine("Hello World!")
End Using
End Using
End Using
End Using
Console.WriteLine("The file was encrypted.")
Catch
Console.WriteLine("The encryption failed.")
Throw
End Try
End Sub
End Module
このコードでは、AES 対称アルゴリズムを使用してストリームを暗号化し、IV を書き込み、ストリームに "Hello World!" を暗号化します。 コードが成功すると、 TestData.txt という名前の暗号化されたファイルが作成され、コンソールに次のテキストが表示されます。
The file was encrypted.
Decrypting Data の対称復号化の例を使用して、ファイルを復号化できます。 この例とこの例では、同じキーを指定します。
ただし、例外が発生した場合、コードはコンソールに次のテキストを表示します。
The encryption failed.
非対称暗号化
非対称アルゴリズムは、通常、対称キーや IV の暗号化など、少量のデータを暗号化するために使用されます。 通常、非対称暗号化を実行する個人は、別のパーティによって生成された公開キーを使用します。 RSAクラスは、この目的のために.NETによって提供されます。
次の例では、公開キー情報を使用して対称キーと IV を暗号化します。 暗号化パーティは、目的の受信者の公開キーを使用します。 この例では、公開キーは RSAParameters 型で表されますが、X.509 SubjectPublicKeyInfo などのファイル形式は、実際のアプリケーションで使用される可能性が高くなります。
Imports System
Imports System.Security.Cryptography
Module Module1
Sub Main()
'Create a new RSA key pair to represent the intended recipient's key.
'The 2048-bit key size shown here is for illustration; choose a key
'size that matches your security requirements per NIST SP 800-57.
Dim recipientRsa As RSA = RSA.Create(2048)
'Export the recipient's public key information.
Dim rsaKeyInfo As RSAParameters = recipientRsa.ExportParameters(False)
'Create a new instance of the default RSA implementation class
'and import the recipient's public key information.
Dim rsa As RSA = RSA.Create()
rsa.ImportParameters(rsaKeyInfo)
'Create a new instance of the default Aes implementation class.
Dim aes As Aes = Aes.Create()
'Encrypt the symmetric key and IV using OAEP padding.
Dim encryptedSymmetricKey As Byte() = rsa.Encrypt(aes.Key, RSAEncryptionPadding.OaepSHA256)
Dim encryptedSymmetricIV As Byte() = rsa.Encrypt(aes.IV, RSAEncryptionPadding.OaepSHA256)
End Sub
End Module
using System;
using System.Security.Cryptography;
class Class1
{
static void Main()
{
// Create a new RSA key pair to represent the intended recipient's key.
// The 2048-bit key size shown here is for illustration; choose a key
// size that matches your security requirements per NIST SP 800-57.
RSA recipientRsa = RSA.Create(2048);
// Export the recipient's public key information.
RSAParameters rsaKeyInfo = recipientRsa.ExportParameters(false);
// Create a new instance of the default RSA implementation class
// and import the recipient's public key information.
RSA rsa = RSA.Create();
rsa.ImportParameters(rsaKeyInfo);
// Create a new instance of the default Aes implementation class.
Aes aes = Aes.Create();
// Encrypt the symmetric key and IV using OAEP padding.
byte[] encryptedSymmetricKey = rsa.Encrypt(aes.Key, RSAEncryptionPadding.OaepSHA256);
byte[] encryptedSymmetricIV = rsa.Encrypt(aes.IV, RSAEncryptionPadding.OaepSHA256);
}
}
参照
.NET