Exaray work areas
Exaray Logo
Home arrow Visual Basic arrow Code Snippets arrow Encrypt, Decrypt and Hash Files
Hauptmenue
Home
Wissen
Visual Basic
News
Downloads
Links
Suche
Administratives
Impressum & Kontakt
Disclaimer
Login





Passwort vergessen?
Noch kein Benutzerkonto?
Registrieren

Keine Zugangsdaten?
Einfach anfordern unter webmaster@exaray.com
Newsflash

Die neue Serverkonfiguration ist online!
Die folgenden Online-Dienste stehen ab sofort zur Verfügung...

weiter …
 

Unser neuer Exchange-Server ist ab sofort auf Exaray umgestellt!

weiter …
 

Unser neuer Asterisk-Server ist ab sofort auf Exaray umgestellt!

weiter …
 
Encrypt, Decrypt and Hash Files PDF Drucken E-Mail
Geschrieben von Lindner Wolfhard   
Friday, 13. March 2009

Public Class frmCrypto
    'Creates the Byte-Key which will be used in subEncryptOrDecryptFile
    'The first 32 bytes of the Password-Hash will be used as the Key
    '
    'Input:
    '    strPassword      The Passsword to encrypt
    'Output:
    '    funCreateKey     The Key to use in subEncryptOrDecryptFile
    '
    Private Function funCreateKey(ByVal strPassword As String) As Byte()
        Try
            'Convert strPassword to an array and store in chrData.
            Dim chrData() As Char = strPassword.ToCharArray
            'Use intLength to get strPassword size.
            Dim intLength As Integer = chrData.GetUpperBound(0)
            'Declare bytDataToHash and make it the same size as chrData.
            Dim bytDataToHash(intLength) As Byte

            'Use For Next to convert and store chrData into bytDataToHash.
            For i As Integer = 0 To chrData.GetUpperBound(0)
                bytDataToHash(i) = CByte(Asc(chrData(i)))
            Next

            'Declare what hash to use.
            Dim SHA512 As New System.Security.Cryptography.SHA512Managed
            'Declare bytResult, Hash bytDataToHash and store it in bytResult.
            Dim bytResult As Byte() = SHA512.ComputeHash(bytDataToHash)
            'Declare bytKey(31).  It will hold 256 bits.
            Dim bytKey(31) As Byte

            'Use For Next to put a specific size (256 bits) of
            'bytResult into bytKey. The 0 To 31 will put the first 256 bits
            'of 512 bits into bytKey.
            For i As Integer = 0 To 31
                bytKey(i) = bytResult(i)
            Next

            Return bytKey 'Return the key.
        Catch ex As Exception
            'ERROR
        End Try
    End Function

    'Creates the Byte-Initialization Vector which will be used in subEncryptOrDecryptFile
    'The first Bytes 32 to 47 of the Password-Hash will be used as the IV
    '
    'Input:
    '    strPassword      The Passsword to encrypt
    'Output:
    '    funCreateIV      The IV to use in subEncryptOrDecryptFile
    '
    Private Function funCreateIV(ByVal strPassword As String) As Byte()
        Try
            'Convert strPassword to an array and store in chrData.
            Dim chrData() As Char = strPassword.ToCharArray
            'Use intLength to get strPassword size.
            Dim intLength As Integer = chrData.GetUpperBound(0)
            'Declare bytDataToHash and make it the same size as chrData.
            Dim bytDataToHash(intLength) As Byte

            'Use For Next to convert and store chrData into bytDataToHash.
            For i As Integer = 0 To chrData.GetUpperBound(0)
                bytDataToHash(i) = CByte(Asc(chrData(i)))
            Next

            'Declare what hash to use.
            Dim SHA512 As New System.Security.Cryptography.SHA512Managed
            'Declare bytResult, Hash bytDataToHash and store it in bytResult.
            Dim bytResult As Byte() = SHA512.ComputeHash(bytDataToHash)
            'Declare bytIV(15).  It will hold 128 bits.
            Dim bytIV(15) As Byte

            'Use For Next to put a specific size (128 bits) of bytResult into bytIV.
            'The 0 To 30 for bytKey used the first 256 bits of the hashed password.
            'The 32 To 47 will put the next 128 bits into bytIV.
            For i As Integer = 32 To 47
                bytIV(i - 32) = bytResult(i)
            Next

            Return bytIV 'Return the IV.
        Catch ex As Exception
            'ERROR
        End Try
    End Function

    Private Enum CryptoAction
        'Define the enumeration for CryptoAction.
        ActionEncrypt = 1
        ActionDecrypt = 2
    End Enum

    'It will encrypt or decrypt a file
    '
    'Input:
    '    strInputFile      The File to encrypt/decrypt
    '    strOutputFile     The encrypted/decrypted output-file
    '    bytKey()          The Key from funCreateKey
    '    bytIV()           The IV from funCreateIV
    '    Direction         Encrypt or decrypt
    '
    Private Sub subEncryptOrDecryptFile(ByVal strInputFile As String, _
                                     ByVal strOutputFile As String, _
                                     ByVal bytKey() As Byte, _
                                     ByVal bytIV() As Byte, _
                                     ByVal Direction As CryptoAction)
        Try 'In case of errors.
            Dim fsInput As System.IO.FileStream
            Dim fsOutput As System.IO.FileStream

            'Setup file streams to handle input and output.
            fsInput = New System.IO.FileStream(strInputFile, FileMode.Open, _
                                                  FileAccess.Read)
            fsOutput = New System.IO.FileStream(strOutputFile, _
                                                   FileMode.OpenOrCreate, _
                                                   FileAccess.Write)
            fsOutput.SetLength(0) 'make sure fsOutput is empty

            'Declare variables for encrypt/decrypt process.
            Dim bytBuffer(4096) As Byte 'holds a block of bytes for processing
            Dim lngBytesProcessed As Long = 0 'running count of bytes processed
            Dim lngFileLength As Long = fsInput.Length 'the input file's length
            Dim intBytesInCurrentBlock As Integer 'current bytes being processed
            Dim csCryptoStream As CryptoStream
            'Declare your CryptoServiceProvider.
            Dim cspRijndael As New System.Security.Cryptography.RijndaelManaged

            'Determine if ecryption or decryption and setup CryptoStream.
            Select Case Direction
                Case CryptoAction.ActionEncrypt
                    csCryptoStream = New CryptoStream(fsOutput, _
                    cspRijndael.CreateEncryptor(bytKey, bytIV), _
                    CryptoStreamMode.Write)

                Case CryptoAction.ActionDecrypt
                    csCryptoStream = New CryptoStream(fsOutput, _
                    cspRijndael.CreateDecryptor(bytKey, bytIV), _
                    CryptoStreamMode.Write)
            End Select

            'Use While to loop until all of the file is processed.
            While lngBytesProcessed < lngFileLength
                'Read file with the input filestream.
                intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096)
                'Write output file with the cryptostream.
                csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock)
                'Update lngBytesProcessed
                lngBytesProcessed = lngBytesProcessed + _
                                        CLng(intBytesInCurrentBlock)
                'Update Progress Bar
                pbStatusFile.Value = CInt((lngBytesProcessed / lngFileLength) * 100) + 200
                Application.DoEvents()
            End While

            'Close FileStreams and CryptoStream.
            csCryptoStream.Close()
            fsInput.Close()
            fsOutput.Close()
        Catch ex As Exception
            If ex.Message = "Zeichenabstände sind ungültig und können nicht entfernt werden." Then
                MsgBox("ACHTUNG: Das Passwort ist falsch! Die Datei kann nicht entschlüsselt werden.")
                Exit Sub
            End If
            'ERROR
        End Try
    End Sub

    'Calculates teh Hash of a file
    '
    'Input:
    '    strFile            The file to hash
    'Output:
    '    funSHA1HashFile    The generated hash of the file
    '
    Public Function funSHA1HashFile(ByVal strFile As String) As String
        Dim SHA1 As New SHA1CryptoServiceProvider
        Dim Hash As Byte()
        Dim Result As String = ""
        Dim Tmp As String = ""

        Try
            Dim FN As New FileStream(strFile, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
            SHA1.ComputeHash(FN)
            FN.Close()

            Hash = SHA1.Hash
            For i As Integer = 0 To Hash.Length - 1
                Tmp = Hex(Hash(i))
                If Len(Tmp) = 1 Then Tmp = "0" & Tmp
                Result += Tmp
            Next
            Return Result
        Catch ex As Exception
            'ERROR
        End Try
    End Function
End Class

 
< zurück   weiter >
   design-cibox.de