Imports System.Security.Cryptography

Public Class EnDec

    Private TripleDes As New TripleDESCryptoServiceProvider
    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

    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

    ''' <summary>
    ''' 문자열의 암호화
    ''' </summary>
    ''' <param name="plaintext"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    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

    ''' <summary>
    ''' 복호화'
    ''' </summary>
    ''' <param name="encryptedtext"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    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, 0, ms.Length)
    End Function

    ''' <summary>
    ''' 파일로부터 문자열을 읽어옵니다.
    ''' </summary>
    ''' <param name="Filename"></param>
    ''' <remarks></remarks>
    Public Function Read_STring(ByVal Filename As String) As String
        Dim FI As New System.IO.FileInfo(Filename)
        If FI.Exists = False Then
            MsgBox("필수파일이 존재하지않습니다", MsgBoxStyle.Critical, "확인")
            Return ""
        End If

        Dim FS As New System.IO.FileStream(FI.FullName, IO.FileMode.Open)
        Dim SR As New System.IO.StreamReader(FS, System.Text.Encoding.Default)

        Dim cipherText As String = SR.ReadToEnd
        SR.Close()
        FS.Close()

        ' DecryptData throws if the wrong password is used.
        Try
            Dim plainText As String = DecryptData(cipherText)
            Return plainText
            'MsgBox("해독값은? " & plainText)
        Catch ex As System.Security.Cryptography.CryptographicException
            Return ""
            MsgBox("암호화키가 일치하지않거나 기타 오류입니다")
        End Try

    End Function

    ''' <summary>
    ''' 파일에 해당 문자열을 기록합니다.
    ''' </summary>
    ''' <param name="Filename"></param>
    ''' <param name="Contents"></param>
    ''' <remarks></remarks>
    Public Sub Write_String(ByVal Filename As String, ByVal Contents As String)
        Dim cipherText As String = EncryptData(Contents)

        Dim FI As New System.IO.FileInfo(Filename)
        Dim FS As New System.IO.FileStream(FI.FullName, IO.FileMode.Create)
        Dim SW As New System.IO.StreamWriter(FS, System.Text.Encoding.Default)
        'MsgBox("암호화된값은? " & cipherText)
        SW.Write(cipherText)
        SW.Flush()
        SW.Close()
        FS.Close()
    End Sub


End Class