このチュートリアルでは DESCryptoServiceProvider クラスを使用して、TDES (Triple Data Encryption Standard) アルゴリズム (TripleDES) の暗号化サービス プロバイダー (CSP: Cryptographic Service Provider) バージョンを用いた文字列の暗号化と復号化を行う方法について説明します。最初に、3DES アルゴリズムをカプセル化し、暗号化されたデータを ベース 64 でエンコードされた文字列として格納する簡単なラッパー クラスを作成します。次に、そのラッパーを使用して、プライベートなユーザー データをパブリックにアクセス可能なテキスト ファイルに安全に格納します。
暗号化を使用すると、ユーザーのシークレット (たとえばパスワードなど) を保護したり、未承認のユーザーによる資格情報の解読を不可能にしたりできます。これにより、承認されたユーザーの ID が盗まれないように保護できるため、ユーザーの資産が保護されます。また、否認が不可能になります。暗号化を行うと、ユーザー データが未承認のユーザーからアクセスされないように保護することも可能になります。
詳細については、「暗号サービス」を参照してください。
セキュリティに関するメモ |
|---|
Rijndael (最近では AES (Advanced Encryption Standard) とも呼ばれる) アルゴリズムや 3DES (Triple Data Encryption Standard) アルゴリズムは、暗号化のための計算量が非常に多いことから、DES よりもかなり高いセキュリティを実現します。詳細については、「DES」および「Rijndael」を参照してください。 |
暗号化のラッパーを作成するには
暗号化と復号化メソッドをカプセル化する Simple3Des のクラスを作成します。
Public NotInheritable Class Simple3Des End ClassSimple3Des のクラスを含むファイルの先頭に、暗号化の名前空間のインポートを追加します。
Imports System.Security.CryptographySimple3Des のクラスでは、3DES暗号化サービス プロバイダーを格納するためのプライベート フィールドを追加します。
Private TripleDes As New TripleDESCryptoServiceProvider指定されたキーのハッシュから指定された長さのバイト配列を作成するプライベート メソッドを追加します。
Private Function TruncateHash( ByVal key As String, ByVal length As Integer) As Byte() Dim sha1 As New SHA1CryptoServiceProvider ' Hash the key. Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key) Dim hash() As Byte = sha1.ComputeHash(keyBytes) ' Truncate or pad the hash. ReDim Preserve hash(length - 1) Return hash End Function3DES 暗号化サービス プロバイダーを初期化するためのコンストラクターを追加します。
key パラメーターは EncryptData メソッドと DecryptData メソッドを制御します。
Sub New(ByVal key As String) ' Initialize the crypto provider. TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8) TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8) End Sub文字列を暗号化するパブリック メソッドを追加します。
Public Function EncryptData( ByVal plaintext As String) As String ' Convert the plaintext string to a byte array. Dim plaintextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the encoder to write to the stream. Dim encStream As New CryptoStream(ms, TripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. encStream.Write(plaintextBytes, 0, plaintextBytes.Length) encStream.FlushFinalBlock() ' Convert the encrypted stream to a printable string. Return Convert.ToBase64String(ms.ToArray) End Function文字列を復号化するパブリック メソッドを追加します。
Public Function DecryptData( ByVal encryptedtext As String) As String ' Convert the encrypted text string to a byte array. Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the decoder to write to the stream. Dim decStream As New CryptoStream(ms, TripleDes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. decStream.Write(encryptedBytes, 0, encryptedBytes.Length) decStream.FlushFinalBlock() ' Convert the plaintext stream to a string. Return System.Text.Encoding.Unicode.GetString(ms.ToArray) End Functionこれで、ラッパークラスを使用してユーザーの資産を保護できるようになりました。ラッパー クラスを使用して、プライベートなユーザー データをパブリックにアクセス可能なテキスト ファイルに安全に格納する例を次に示します。
暗号化のラッパーをテストするには
別のクラスで、ラッパーの EncryptData メソッドを使用して文字列を暗号化し、それをユーザーのマイ ドキュメント フォルダーに書き込むメソッドを追加します。
Sub TestEncoding() Dim plainText As String = InputBox("Enter the plain text:") Dim password As String = InputBox("Enter the password:") Dim wrapper As New Simple3Des(password) Dim cipherText As String = wrapper.EncryptData(plainText) MsgBox("The cipher text is: " & cipherText) My.Computer.FileSystem.WriteAllText( My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\cipherText.txt", cipherText, False) End Sub暗号化された文字列を、ユーザーのマイ ドキュメント フォルダーから読み取り、その文字列をラッパーの DecryptData メソッドを使って復号化するメソッドを追加します。
Sub TestDecoding() Dim cipherText As String = My.Computer.FileSystem.ReadAllText( My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\cipherText.txt") Dim password As String = InputBox("Enter the password:") Dim wrapper As New Simple3Des(password) ' DecryptData throws if the wrong password is used. Try Dim plainText As String = wrapper.DecryptData(cipherText) MsgBox("The plain text is: " & plainText) Catch ex As System.Security.Cryptography.CryptographicException MsgBox("The data could not be decrypted with the password.") End Try End SubTestEncoding メソッドと TestDecoding メソッドを呼び出すためのユーザー インターフェイス コードを追加します。
アプリケーションを実行します。
アプリケーションをテストするとき、間違ったパスワードを入力するとデータが復号化されないので注意してください。
セキュリティに関するメモ