다음을 통해 공유


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

이 연습에서는 DESCryptoServiceProvider 클래스에서 Triple DES(TripleDES) 알고리즘의 CSP(Cryptographic Service Provider) 버전을 사용하여 문자열을 암호화하고 해독하는 방법을 보여 줍니다. 첫 번째 단계에서는 3DES 알고리즘을 캡슐화하고 암호화된 데이터를 Base-64 인코딩된 문자열로 저장하는 간단한 래퍼 클래스를 만듭니다. 그런 다음 해당 래퍼를 사용하여 개인 사용자 데이터를 공개적으로 액세스 가능한 텍스트 파일에 안전하게 저장합니다.

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

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

보안 정보보안 정보

Rijndael(AES[Advanced Encryption Standard]) 및 3DES(Triple Data Encryption Standard) 알고리즘을 사용하면 계산이 더 복잡하므로 DES를 사용할 때보다 보안을 강화할 수 있습니다. 자세한 내용은 DESRijndael을 참조하십시오.

암호화 래퍼를 만들려면

  1. 암호화 네임스페이스 가져오기를 파일 시작 지점에 추가합니다.

    Imports System.Security.Cryptography
    
  2. 암호화 및 해독 메서드를 캡슐화하는 클래스를 만듭니다.

    Public NotInheritable Class Simple3Des
    End Class
    
  3. 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. 응용 프로그램을 실행합니다.

    응용 프로그램을 테스트할 때 잘못된 암호를 제공하면 데이터가 해독되지 않습니다.

참고 항목

참조

System.Security.Cryptography

DESCryptoServiceProvider

DES

TripleDES

Rijndael

개념

암호화 서비스