이 연습에서는 클래스를 사용하여 TripleDES 3DES(Triple Data Encryption Standard) 알고리즘을 사용하여 문자열을 암호화하고 암호 해독하는 방법을 보여 줍니다. 첫 번째 단계는 3DES 알고리즘을 캡슐화하고 암호화된 데이터를 base-64로 인코딩된 문자열로 저장하는 간단한 래퍼 클래스를 만드는 것입니다. 그런 다음, 해당 래퍼는 공개적으로 액세스할 수 있는 텍스트 파일에 개인 사용자 데이터를 안전하게 저장하는 데 사용됩니다.
암호화를 사용하여 사용자 비밀(예: 암호)을 보호하고 권한이 없는 사용자가 자격 증명을 읽을 수 없도록 만들 수 있습니다. 이렇게 하면 권한 있는 사용자의 ID가 도난당하지 않도록 보호할 수 있으며, 이는 사용자의 자산을 보호하고 부인할 수 없습니다. 암호화는 권한이 없는 사용자가 사용자의 데이터에 액세스하지 못하도록 보호할 수도 있습니다.
자세한 내용은 Cryptographic Services를 참조하세요.
중요합니다
Rijndael(현재는 고급 암호화 표준 [AES]이라고 함) 및 3DES(Triple Data Encryption Standard) 알고리즘은 계산 집약적이기 때문에 DES보다 더 큰 보안을 제공합니다. 자세한 내용은 DES 및 Rijndael참조하세요.
암호화 래퍼를 만들려면
Simple3Des암호화 및 암호 해독 메서드를 캡슐화하는 클래스를 만듭니다.Public NotInheritable Class Simple3Des End Class파일의 시작 부분에
Simple3Des클래스를 포함하는 암호화 네임스페이스 가져오기를 추가합니다.Imports System.Security.Cryptography클래스에서
Simple3Des3DES 암호화 서비스 공급자를 저장할 프라이빗 필드를 추가합니다.Private TripleDes As TripleDES = TripleDES.Create()지정된 키의 해시에서 지정된 길이의 바이트 배열을 만드는 private 메서드를 추가합니다.
Private Function TruncateHash( ByVal key As String, ByVal length As Integer) As Byte() Using sha256 As SHA256 = SHA256.Create() ' Hash the key. Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key) Dim hash() As Byte = sha256.ComputeHash(keyBytes) ' Truncate or pad the hash. ReDim Preserve hash(length - 1) Return hash End Using End Function생성자를 추가하여 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문자열을 암호화하는 공용 메서드를 추가합니다.
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 메서드를 추가합니다.
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메서드를 호출하기 위해 사용자 인터페이스 코드를 추가하세요.애플리케이션을 실행합니다.
애플리케이션을 테스트할 때 잘못된 암호를 제공하는 경우 데이터의 암호를 해독하지 않습니다.
참고하십시오
.NET