VB.Net/File Directory/Cypher Decypher File

Материал из VB Эксперт
Перейти к: навигация, поиск

Decrypt a Des Encryted File

 
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.IO
Imports System.Data.OleDb
Imports System.Data.rumon
Imports System.Data.SqlClient
Imports System.Data
Imports System.Security
Imports System.Security.Cryptography

Public Class MainClass
    
    Shared Sub Main()
        Dim fs As FileStream = New FileStream("DSencrypted.dat",FileMode.Create, FileAccess.Write)
        Dim MyDS As DataSet = New DataSet()
        Dim MyDS2 As DataSet = New DataSet()
        Dim Connection As SqlConnection = New SqlConnection("Server=(local)\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=SSPI")
        Connection.Open()
        Dim MyDA As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM Employee", Connection)
        MyDA.Fill(MyDS, "Employee")
        Dim DES As DESCryptoServiceProvider = New DESCryptoServiceProvider()
        Dim DESencrypter As ICryptoTransform = DES.CreateEncryptor()
        Dim cryptStream As CryptoStream = New CryptoStream(fs, DESencrypter, CryptoStreamMode.Write)
        MyDS.WriteXml(cryptStream, XmlWriteMode.WriteSchema)
        cryptStream.Close()

        Dim fsRead As FileStream = New FileStream("DSencrypted.dat", _
           FileMode.Open, FileAccess.Read)
        Dim DESdecrypter As ICryptoTransform = DES.CreateDecryptor()
        Dim decryptStream As CryptoStream = New CryptoStream(fsRead, _
           DESdecrypter, CryptoStreamMode.Read)
        Dim plainStreamR As XmlTextReader = New XmlTextReader(decryptStream)
        MyDS2.ReadXml(plainStreamR, XmlReadMode.ReadSchema)
    End Sub
End Class


Encrypting a file

  
Imports System.Security.Cryptography
Module MainModule
    Public Function GenerateKey() As Byte()
        Dim objDES As New System.Security.Cryptography.DESCryptoServiceProvider()
        objDES.GenerateKey()
        Return objDES.Key
    End Function
    Public Function GenerateIV() As Byte()
        Dim objDES As New System.Security.Cryptography.DESCryptoServiceProvider()
        objDES.GenerateIV()
        Return objDES.IV
    End Function
    Public Sub SaveEncryptedFile(ByVal Key() As Byte, ByVal IV() As Byte, ByVal Data As String, ByVal Filename As String)
        Dim objFileStream As New System.IO.FileStream(Filename, System.IO.FileMode.Create, System.IO.FileAccess.Write)
        Dim bytInput As Byte() = New System.Text.UnicodeEncoding().GetBytes(Data)
        Dim objDES As New DESCryptoServiceProvider()
        objDES.Key = Key
        objDES.IV = IV
        Dim objDESEncrypt As ICryptoTransform = objDES.CreateEncryptor()
        Dim objCryptStream As New CryptoStream(objFileStream, objDESEncrypt, CryptoStreamMode.Write)
        objCryptStream.Write(bytInput, 0, bytInput.Length)
        objCryptStream.Close()
        objFileStream.Close()
    End Sub
    Public Function LoadEncryptedFile(ByVal Key() As Byte, ByVal IV() As Byte, ByVal Filename As String) As String
        Dim objFileStream As New System.IO.FileStream(Filename, System.IO.FileMode.Open, System.IO.FileAccess.Read)
        Dim objDES As New DESCryptoServiceProvider()
        objDES.Key = Key
        objDES.IV = IV
        Dim objDESDecrypt As ICryptoTransform = objDES.CreateDecryptor()
        Dim objCryptStream As New CryptoStream(objFileStream, objDESDecrypt, CryptoStreamMode.Read)
        LoadEncryptedFile = New System.IO.StreamReader(objCryptStream, New System.Text.UnicodeEncoding()).ReadToEnd()
        objCryptStream.Close()
        objFileStream.Close()
    End Function
End Module


Use DES, RC2, Rijndael, TripleDES to decrypt and Encrypt files

 
Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Imports System
Public Class SymEnc
    Shared Dim algorithms() As String = {"DES", "RC2", "Rijndael", "TripleDES"}
    Shared Dim b64Keys() As String = {"YE32PGCJ/g0=","vct+rJ09WuUcR61yfxniTQ==","PHDPqfwE3z25f2UYjwwfwg4XSqxvl8WYmy+2h8t6AUg=","Q1/lWoraddTH3IXAQUJGDSYDQcYYuOpm"}
    Shared Dim b64IVs() As String = {"onQX8hdHeWQ=","jgetiyz+pIc=","pd5mgMMfDI2Gxm/SKl5I8A==","6jpFrUh8FF4="}
    Public Shared Sub Main(ByVal CmdArgs() As String)
        If (CmdArgs.Length <> 4) Then
            UsageAndExit()
        End If
        Dim algorithmsIndex As Integer = CmdArgs(0)
        If (algorithmsIndex < 0 Or algorithmsIndex >= algorithms.Length) Then
            UsageAndExit()
        End If
        
        
        Dim inputFile As FileStream = File.OpenRead(CmdArgs(2))
        Dim outputFile As FileStream = File.OpenWrite(CmdArgs(3))
        Dim sa As SymmetricAlgorithm = SymmetricAlgorithm.Create(algorithms(algorithmsIndex))
        
        sa.IV = Convert.FromBase64String(b64IVs(algorithmsIndex))
        sa.Key = Convert.FromBase64String(b64Keys(algorithmsIndex))
        If (CmdArgs(1).ToUpper().StartsWith("E")) Then
            Encrypt(sa, inputFile, outputFile)
        Else
            Decrypt(sa, inputFile, outputFile)
        End If
        
    End Sub
    Shared Public Sub Encrypt(ByVal sa As SymmetricAlgorithm,ByVal inputFile As Stream,ByVal outputFile As Stream)
        Dim trans As ICryptoTransform = sa.CreateEncryptor()
        Dim buf() As Byte = New Byte(2048) {}
        Dim cs As CryptoStream = _
        New CryptoStream(outputFile, trans, CryptoStreamMode.Write)
        Dim Len As Integer
        inputFile.Position = 0
        Len = inputFile.Read(buf, 0, buf.Length)
        While (Len > 0)
            cs.Write(buf, 0, Len)
            Len = inputFile.Read(buf, 0, buf.Length)
        End While
        cs.Close()
        inputFile.Close()
    End Sub
    Shared Public Sub Decrypt(ByVal sa As SymmetricAlgorithm,ByVal inputFile As Stream,ByVal outputFile As Stream)
        Dim trans As ICryptoTransform = sa.CreateDecryptor()
        Dim buf() As Byte = New Byte(2048) {}
        Dim cs As CryptoStream = _
        New CryptoStream(inputFile, trans, CryptoStreamMode.Read)
        Dim Len As Integer
        Len = cs.Read(buf, 0, buf.Length)
        While (Len > 0)
            outputFile.Write(buf, 0, Len)
            Len = cs.Read(buf, 0, buf.Length)
        End While
        inputFile.Close()
        outputFile.Close()
    End Sub
    Shared Public Sub UsageAndExit()
        Console.Write("usage SymEnc <algorithms index> <D|E> <in> <out> ")
        Console.WriteLine("D =decrypt, E=Encrypt")
        For i As Integer = 0 To (algorithms.Length - 1)
            Console.WriteLine("Algo index: {0} {1}", i, algorithms(i))
        Next i
        End
    End Sub
End Class


Use Des to cypher and decypher File

 
Imports System
Imports System.Windows.Forms
Imports System.Security
Imports System.Security.Cryptography
Imports System.IO
Public Class MainClass
   Shared Sub Main()
        Dim plainTextFileName As String = "test.txt"
        Dim cypherTextFileName As String = "cyphertext.dat"
        Dim decypheredFileName As String = "decyphered.txt"
        CryptFile("MyPassword", plainTextFileName, cypherTextFileName, True)
        Console.WriteLine( File.ReadAllText(plainTextFileName))
        Console.WriteLine( File.ReadAllText(cypherTextFileName))
        CryptFile("MyPassword", cypherTextFileName, decypheredFileName, False)
        Console.WriteLine( File.ReadAllText(decypheredFileName))
   End Sub 
    " Encrypt or decrypt a file, saving the results 
    " in another file.
    Shared Private Sub CryptFile(ByVal password As String, ByVal in_file As String, ByVal out_file As String, ByVal encrypt As Boolean)
        " Create input and output file streams.
        Dim in_stream As New FileStream(in_file, FileMode.Open, FileAccess.Read)
        Dim out_stream As New FileStream(out_file, FileMode.Create, FileAccess.Write)
        Dim des_provider As New TripleDESCryptoServiceProvider()
        " Find a valid key size for this provider.
        Dim key_size_bits As Integer = 0
        For i As Integer = 1024 To 1 Step -1
            If des_provider.ValidKeySize(i) Then
                key_size_bits = i
                Exit For
            End If
        Next i
        "Debug.Assert(key_size_bits > 0)
        Dim block_size_bits As Integer = des_provider.BlockSize
        Dim key As Byte() = Nothing
        Dim iv As Byte() = Nothing
        MakeKeyAndIV(password, key_size_bits, block_size_bits, key, iv)
        Dim crypto_transform As ICryptoTransform
        If encrypt Then
            crypto_transform = des_provider.CreateEncryptor(key, iv)
        Else
            crypto_transform = des_provider.CreateDecryptor(key, iv)
        End If
        Dim crypto_stream As New CryptoStream(out_stream, crypto_transform, CryptoStreamMode.Write)
        Const BLOCK_SIZE As Integer = 1024
        Dim buffer(BLOCK_SIZE) As Byte
        Dim bytes_read As Integer
        Do
            bytes_read = in_stream.Read(buffer, 0, BLOCK_SIZE)
            If bytes_read = 0 Then Exit Do
            crypto_stream.Write(buffer, 0, bytes_read)
        Loop
        crypto_stream.Close()
        in_stream.Close()
        out_stream.Close()
    End Sub
    " Use the password to generate key bytes.
    Shared Private Sub MakeKeyAndIV(ByVal password As String, ByVal key_size_bits As Integer, ByVal block_size_bits As Integer, ByRef key As Byte(), ByRef iv As Byte())
        Dim password_derive_bytes As New PasswordDeriveBytes( _
            "MyPassword", Nothing, "SHA384", 1000)
        key = password_derive_bytes.GetBytes(key_size_bits \ 8)
        iv = password_derive_bytes.GetBytes(block_size_bits \ 8)
    End Sub
End Class