次の方法で共有


チュートリアル: Visual Basic での文字列の暗号化と暗号化解除

このチュートリアルでは、DESCryptoServiceProvider クラスを使用して、Triple Data Encryption Standard (TripleDES) アルゴリズムの暗号化サービス プロバイダー (CSP) バージョンを使用して文字列を暗号化および復号化する方法について説明します。 最初の手順は、3DES アルゴリズムをカプセル化し、暗号化されたデータを base-64 エンコード文字列として格納する単純なラッパー クラスを作成することです。 次に、そのラッパーを使用して、プライベート ユーザー データをパブリックにアクセス可能なテキスト ファイルに安全に格納します。

暗号化を使用すると、ユーザー シークレット (パスワードなど) を保護し、承認されていないユーザーが資格情報を読み取れないようにすることができます。 これにより、承認されたユーザーの ID を盗難から保護し、ユーザーの資産を保護し、否認防止を提供することができます。 暗号化を使用すると、承認されていないユーザーによるアクセスからユーザーのデータを保護することもできます。

詳細については、「暗号サービス」をご覧ください。

重要

Rijndael (現在は Advanced Encryption Standard [AES] と呼ばれています) アルゴリズムと Triple Data Encryption Standard (3DES) アルゴリズムは、計算量が多いため、DES よりも優れたセキュリティを実現できます。 詳細については、次のトピックを参照してください。 DES および Rijndael

暗号化ラッパーを作成するには

  1. Simple3Des クラスを作成して、暗号化方法と復号化方法をカプセル化します。

    Public NotInheritable Class Simple3Des
    End Class
    
  2. 暗号化名前空間のインポートを Simple3Des クラスを含むファイルの先頭に追加します。

    Imports System.Security.Cryptography
    
  3. Simple3Des クラスで、3DES 暗号化サービス プロバイダーを格納するプライベート フィールドを追加します。

    Private TripleDes As New TripleDESCryptoServiceProvider
    
  4. 指定されたキーのハッシュから指定された長さのバイト配列を作成するプライベート メソッドを追加します。

    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 Function
    
  5. 3DES 暗号化サービス プロバイダーを初期化するコンストラクターを追加します。

    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
    
  6. 文字列を暗号化するパブリック メソッドを追加します。

    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
    
  7. 文字列を復号化するパブリック メソッドを追加します。

    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
    

    これで、ラッパー クラスを使用してユーザー資産を保護できるようになりました。 この例では、パブリックにアクセスできるテキスト ファイルにプライベート ユーザー データを安全に格納するために使用されます。

暗号化ラッパーをテストするには

  1. 別のクラスで、ラッパーの 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
    
  2. ユーザーのマイ ドキュメント フォルダーから暗号化された文字列を読み取り、ラッパーの 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 Sub
    
  3. TestEncoding メソッドと TestDecoding メソッドを呼び出すユーザー インターフェイス コードを追加します。

  4. アプリケーションを実行します。

    アプリケーションをテストするときに間違ったパスワードを指定した場合、データが復号化されないことに注意してください。

関連項目