이 연습에서는 클래스를 사용하여 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.CryptographySimple3Des클래스에서 프라이빗 필드를 추가하여 3DES 암호화 서비스 공급자, 지정된 키 및 형식 버전, 솔트 크기 및 반복 횟수를 저장합니다.Private TripleDes As TripleDES = TripleDES.Create() Private Const FormatVersion As Byte = 1 Private Const SaltSize As Integer = 16 Private Const Iterations As Integer = 600000 Private ReadOnly Key As String지정된 키와 솔트에서 바이트 배열을 만드는 private 메서드를 추가합니다.
Private Function DeriveKey(ByVal salt() As Byte) As Byte() ' Derive a key from the specified key and the salt. Using kdf As New Rfc2898DeriveBytes( Key, salt, Iterations, HashAlgorithmName.SHA256) Return kdf.GetBytes(TripleDes.KeySize \ 8) End Using End Function지정된 키를 저장하는 생성자를 추가합니다.
key매개변수는EncryptData및DecryptData메서드를 제어합니다.Sub New(ByVal key As String) ' Store the key. The encryption key and IV are created per message. Me.Key = key End Sub문자열을 암호화하는 공용 메서드를 추가합니다.
Public Function EncryptData( ByVal plaintext As String) As String ' Create a new salt and initialization vector for this message. Dim salt(SaltSize - 1) As Byte Using rng As RandomNumberGenerator = RandomNumberGenerator.Create() rng.GetBytes(salt) End Using TripleDes.Key = DeriveKey(salt) TripleDes.GenerateIV() ' 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 ' Write the format version, salt, and initialization vector in front of ' the cipher text. The version identifies the salt length and iteration count. ms.WriteByte(FormatVersion) ms.Write(salt, 0, salt.Length) ms.Write(TripleDes.IV, 0, TripleDes.IV.Length) ' 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) ' Read the header that precedes the cipher text. Only one format ' version exists, so reject anything else. Dim ivSize As Integer = TripleDes.BlockSize \ 8 Dim headerSize As Integer = 1 + SaltSize + ivSize If encryptedBytes.Length < headerSize OrElse encryptedBytes(0) <> FormatVersion Then Throw New CryptographicException( "The encrypted data is not in the expected format.") End If Dim salt(SaltSize - 1) As Byte Dim iv(ivSize - 1) As Byte Array.Copy(encryptedBytes, 1, salt, 0, SaltSize) Array.Copy(encryptedBytes, 1 + SaltSize, iv, 0, ivSize) TripleDes.Key = DeriveKey(salt) TripleDes.IV = iv ' 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, headerSize, encryptedBytes.Length - headerSize) 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