연습: Visual Basic에서 문자열 암호화 및 암호 해독

이 연습에서는 DESCryptoServiceProvider 클래스를 사용하여 Triple Data Encryption Standard(TripleDES) 알고리즘의 CSP(암호화 서비스 공급자) 버전을 사용하여 문자열을 암호화하고 암호 해독하는 방법을 보여 줍니다. 첫 번째 단계는 3DES 알고리즘을 캡슐화하고 암호화된 데이터를 base-64로 인코딩된 문자열로 저장하는 간단한 래퍼 클래스를 만드는 것입니다. 그런 다음, 해당 래퍼는 공개적으로 액세스할 수 있는 텍스트 파일에 개인 사용자 데이터를 안전하게 저장하는 데 사용됩니다.

암호화를 사용하여 사용자 비밀(예: 암호)을 보호하고 권한이 없는 사용자가 자격 증명을 읽지 못하도록 만들 수 있습니다. 이렇게 하면 권한 있는 사용자의 ID가 도용되는 것을 방지하여 사용자의 자산을 보호하고 부인 방지 기능을 제공할 수 있습니다. 암호화는 권한이 없는 사용자가 사용자의 데이터에 액세스하지 못하도록 보호할 수도 있습니다.

자세한 내용은 암호화 서비스를 참조하세요.

Important

Rijndael(현재는 AES(Advanced Encryption Standard)라고 함) 및 3DES(Triple Data Encryption Standard) 알고리즘은 계산 집약적이기 때문에 DES보다 강력한 보안을 제공합니다. 자세한 내용은 DESRijndael를 참조하세요.

암호화 래퍼를 만들려면

  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 매개 변수는 EncryptDataDecryptData 메서드를 제어합니다.

    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. TestEncodingTestDecoding 메서드를 호출하는 사용자 인터페이스 코드를 추가합니다.

  4. 애플리케이션을 실행합니다.

    애플리케이션을 테스트할 때 잘못된 암호를 제공하는 경우 데이터를 해독하지 못합니다.

참고 항목