Как конвертировать vb.net к vb6
Я написал код на C# и vb.net но теперь требование заключается в VB6.Могу ли я конвертировать vb.net код для vb6.Как добавить пространство имен в систему vb6.Безопасность.Криптография
Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Security.Cryptography Imports System.IO Namespace RijndaelEncDec Public Enum CryptoEventType Message FileProgress End Enum Public Class CryptoEventArgs Inherits EventArgs Private m_type As CryptoEventType Private m_message As String Private m_fileLength As Integer Private m_filePosition As Integer Public Sub New(ByVal message As String) m_type = CryptoEventType.Message Me.m_message = message End Sub Public Sub New(ByVal fileName As String, ByVal fileLength As Integer, ByVal filePosition As Integer) m_type = CryptoEventType.FileProgress Me.m_fileLength = fileLength Me.m_filePosition = filePosition m_message = fileName End Sub Public ReadOnly Property Type() As CryptoEventType Get Return m_type End Get End Property Public ReadOnly Property Message() As String Get Return m_message End Get End Property Public ReadOnly Property FileName() As String Get Return m_message End Get End Property Public ReadOnly Property FileLength() As Integer Get Return m_fileLength End Get End Property Public ReadOnly Property FilePosition() As Integer Get Return m_filePosition End Get End Property End Class Public Delegate Sub cryptoEventHandler(ByVal sender As Object, ByVal e As CryptoEventArgs) ''' <summary> ''' ''' </summary> Public Class CryptoManager Private testHeader As Byte() = Nothing 'used to verify if decryption succeeded Private testHeaderString As String = Nothing Public Sub New() testHeader = System.Text.Encoding.ASCII.GetBytes("testing header") testHeaderString = BitConverter.ToString(testHeader) End Sub Public Sub getKeysFromPassword(ByVal pass As String, ByRef rijnKey As Byte(), ByRef rijnIV As Byte()) Dim salt As Byte() = System.Text.Encoding.ASCII.GetBytes("System.Text.Encoding.ASCII.GetBytes") Dim pb As New PasswordDeriveBytes(pass, salt) rijnKey = pb.GetBytes(32) rijnIV = pb.GetBytes(16) End Sub Const bufLen As Integer = 4096 Public Sub EncryptData(ByVal inName As [String], ByVal outName As [String], ByVal rijnKey As Byte(), ByVal rijnIV As Byte()) Dim fin As FileStream = Nothing Dim fout As FileStream = Nothing Dim encStream As CryptoStream = Nothing Try 'Create the file streams to handle the input and output files. fin = New FileStream(inName, FileMode.Open, FileAccess.Read) fout = New FileStream(outName, FileMode.Create, FileAccess.Write) 'Create variables to help with read and write. Dim bin As Byte() = New Byte(bufLen - 1) {} 'This is intermediate storage for the encryption. Dim rdlen As Long = 0 'This is the total number of bytes written. Dim totlen As Long = fin.Length 'This is the total length of the input file. Dim len As Integer 'This is the number of bytes to be written at a time. Dim rijn As New RijndaelManaged() rijn.Mode = CipherMode.CBC rijn.KeySize = 256 rijn.BlockSize = 128 rijn.Padding = PaddingMode.PKCS7 encStream = New CryptoStream(fout, rijn.CreateEncryptor(rijnKey, rijnIV), CryptoStreamMode.Write) 'zakoduj testowy fragment encStream.Write(testHeader, 0, testHeader.Length) 'Read from the input file, then encrypt and write to the output file. While True len = fin.Read(bin, 0, bufLen) If len = 0 Then Exit While End If encStream.Write(bin, 0, len) rdlen += len End While Finally If encStream IsNot Nothing Then encStream.Close() End If If fout IsNot Nothing Then fout.Close() End If If fin IsNot Nothing Then fin.Close() End If End Try End Sub Public Sub EncryptBuffer(ByVal buffer As [String], ByVal outName As [String], ByVal rijnKey As Byte(), ByVal rijnIV As Byte()) Dim fin As FileStream = Nothing Dim fout As FileStream = Nothing Dim encStream As CryptoStream = Nothing Try 'Create the file streams to handle the input and output files. ' fin = new FileStream((inName, FileMode.Open, FileAccess.Read); Dim byteArray As Byte() = Encoding.ASCII.GetBytes(buffer) Dim mem As New MemoryStream(byteArray) fout = New FileStream(outName, FileMode.Create, FileAccess.Write) 'Create variables to help with read and write. Dim bin As Byte() = New Byte(bufLen - 1) {} 'This is intermediate storage for the encryption. Dim rdlen As Long = 0 'This is the total number of bytes written. Dim totlen As Long = mem.Length 'This is the total length of the input file. Dim len As Integer 'This is the number of bytes to be written at a time. Dim rijn As New RijndaelManaged() rijn.Mode = CipherMode.CBC rijn.KeySize = 256 rijn.BlockSize = 128 rijn.Padding = PaddingMode.PKCS7 encStream = New CryptoStream(fout, rijn.CreateEncryptor(rijnKey, rijnIV), CryptoStreamMode.Write) 'zakoduj testowy fragment encStream.Write(testHeader, 0, testHeader.Length) 'Read from the input file, then encrypt and write to the output file. While True len = mem.Read(bin, 0, bufLen) If len = 0 Then Exit While End If encStream.Write(bin, 0, len) rdlen += len End While Finally If encStream IsNot Nothing Then encStream.Close() End If If fout IsNot Nothing Then fout.Close() End If If fin IsNot Nothing Then fin.Close() End If End Try End Sub Public Function DecryptData(ByVal inName As [String], ByVal outName As [String], ByVal rijnKey As Byte(), ByVal rijnIV As Byte()) As Boolean 'Create the file streams to handle the input and output files. Dim fin As FileStream = Nothing Dim fout As FileStream = Nothing Dim decStream As CryptoStream = Nothing Try fin = New FileStream(inName, FileMode.Open, FileAccess.Read) 'Create variables to help with read and write. Dim bin As Byte() = New Byte(bufLen - 1) {} 'This is intermediate storage for the encryption. Dim rdlen As Long = 0 'This is the total number of bytes written. Dim totlen As Long = fin.Length 'This is the total length of the input file. Dim len As Integer 'This is the number of bytes to be written at a time. Dim rijn As New RijndaelManaged() rijn.Mode = CipherMode.CBC rijn.KeySize = 256 rijn.BlockSize = 128 rijn.Padding = PaddingMode.PKCS7 'DES ds = new DESCryptoServiceProvider(); decStream = New CryptoStream(fin, rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Read) 'odkoduj testowy fragment Dim test As Byte() = New Byte(testHeader.Length - 1) {} decStream.Read(test, 0, testHeader.Length) If BitConverter.ToString(test) <> testHeaderString Then decStream.Clear() decStream = Nothing Return False End If 'create output file fout = New FileStream(outName, FileMode.Create, FileAccess.Write) 'Read from the encrypted file and write dercypted data While True len = decStream.Read(bin, 0, bufLen) If len = 0 Then Exit While End If fout.Write(bin, 0, len) rdlen += len End While Return True Finally If decStream IsNot Nothing Then decStream.Close() End If If fout IsNot Nothing Then fout.Close() End If If fin IsNot Nothing Then fin.Close() End If End Try End Function End Class Public Class Log Public Shared logPermission As Boolean = True Public Shared logFileLocation As [String] = "D:\C#EncDecLogFile.txt" End Class Public Class Rijndael Private pwd As String = "" Private testHeader As Byte() = Nothing 'used to verify if decryption succeeded Private testHeaderString As String = Nothing Private cryptoKey As Byte(), cryptoIV As Byte() Private crm As New CryptoManager() Public Sub getPassword() Try pwd = "1234567890" 'get keys from password Dim dk As Byte() = Nothing Dim div As Byte() = Nothing crm.getKeysFromPassword(pwd, dk, div) cryptoKey = dk cryptoIV = div Catch ex As FormatException Return End Try End Sub Public Sub Encryption(ByVal filePath As String) 'sunil code with RSA getPassword() Const PROVIDER_RSA_FULL As Integer = 1 Const CONTAINER_NAME As String = "KeyContainer" Dim cspParams As CspParameters cspParams = New CspParameters(PROVIDER_RSA_FULL) cspParams.KeyContainerName = CONTAINER_NAME cspParams.Flags = CspProviderFlags.UseMachineKeyStore cspParams.ProviderName = "Microsoft Strong Cryptographic Provider" Dim originalPath As String = filePath.Substring(0, filePath.LastIndexOf("\")) Try Dim current As DateTime = DateTime.Now Dim RSA As New RSACryptoServiceProvider(cspParams) Dim keyToEncrypt As Byte() Dim encryptedKey As Byte() Dim origName As String = filePath Dim encName As String = origName & ".enc" Try crm.EncryptData(origName, encName, cryptoKey, cryptoIV) Dim fi As New FileInfo(origName) Dim fi2 As New FileInfo(encName) 'remove readonly attribute If (fi.Attributes And FileAttributes.[ReadOnly]) = FileAttributes.[ReadOnly] Then fi.Attributes = fi.Attributes And Not FileAttributes.[ReadOnly] End If 'copy creation and modification time fi2.CreationTime = fi.CreationTime fi2.LastWriteTime = fi.LastWriteTime fi2.Attributes = FileAttributes.Normal Or FileAttributes.Archive Dim data As Byte() = File.ReadAllBytes(encName) 'delete original file File.Delete(encName) '#Region "write RSA (Public Private) key in xml files" Dim publicprivatexml As String = RSA.ToXmlString(True) '#End Region keyToEncrypt = System.Text.ASCIIEncoding.Unicode.GetBytes(pwd) encryptedKey = RSA.Encrypt(keyToEncrypt, False) 'using (BinaryWriter bw = new BinaryWriter(File.Create(origName + " " + current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString() + ".enc"))) Using bw As New BinaryWriter(File.Create(originalPath & "\Encrypted.enc")) 'Write data bw.Seek(0, SeekOrigin.Begin) bw.Write(data) bw.Write(encryptedKey) bw.Close() 'MessageBox.Show("File Encrypted"); End Using ' MessageBox.Show(ex.Message); Catch ex As CryptographicException 'MessageBox.Show(ex.Message); Catch ex As IOException 'i.e. readonly ' MessageBox.Show(ex.Message); Catch ex As UnauthorizedAccessException End Try 'MessageBox.Show(ex.Message); Catch ex As Exception End Try End Sub Public Sub Decryption(ByVal filePath As String) 'sunil code with RSA Const PROVIDER_RSA_FULL As Integer = 1 Const CONTAINER_NAME As String = "KeyContainer" Dim cspParams As CspParameters cspParams = New CspParameters(PROVIDER_RSA_FULL) cspParams.KeyContainerName = CONTAINER_NAME cspParams.Flags = CspProviderFlags.UseMachineKeyStore cspParams.ProviderName = "Microsoft Strong Cryptographic Provider" Dim originalPath As String = filePath.Substring(0, filePath.LastIndexOf("\")) Try Dim current As DateTime = DateTime.Now Dim encName As String = filePath & "data" & ".enc" Dim RSA As New RSACryptoServiceProvider(cspParams) '#Region "Seperate key and data" Dim alldata As Byte() = File.ReadAllBytes(filePath) Dim getencryptedkey As Byte() = New Byte(127) {} Dim data As Byte() = New Byte(alldata.Length - 129) {} For k As Integer = 0 To alldata.Length - 129 data(k) = alldata(k) Next Dim i As Integer = alldata.Length - 128, j As Integer = 0 While i < alldata.Length getencryptedkey(j) = alldata(i) i += 1 j += 1 End While Using bw As New BinaryWriter(File.Create(encName)) bw.Write(data) bw.Close() End Using Dim publicprivatekeyxml As String = "<rsakeyvalue><modulus>qwJYZm7ECFuktmofbVkm4J1kRf/L9521P70DaJhw/JNCwmCVItuaGEZWUlPZoMB6Q05Da7yYhkhVTHbybyxTcSMeQBsXb8jVqm3HWN3Quy8XITjGkuCsP8AijmXVV2RWa8T1oklN5SZfdaprue0ZWLjUFcZff5eay4igWjXpmVE=</modulus><exponent>AQAB</exponent><p>6RxsBsub9tG0hwRS92vLjxUuBF5adjifmLvB3cr1RnwcgX7EoVWiw/UPBzfiF/B9ZYkvu5EnL3ZTZ0Uae0eDrw==</p><q>u8zniy7nrMDyZHgnMR1yaL/w/bw0jPelo9t3h/1yOetFBRDYKGQQc3njLl/I8NIm0grug+x43vSOprh65m7y/w==</q><dp>ooqX5JEaehq1FyPzuePm9yjcgl1MFHzdA8F/p2g6aGBn+/9pmdk9egeo5+6WbvzYYvEqYE4RFa4a77omgelWrw==</dp><dq>lcTGjzgb6KiDZl5wGvo56JHSNfhnDFjfTzrSK7CS7N/UzkJtsGCEwiLda3lV/cAK142CQ9FNX7k3HnyW/rhSrw==</dq><inverseq>qni6yLGiI0ZsSabZutS+OI+qF8paE4+CMBQxj6BOt/35msm+L8kc+sqgsghy/MoZDnlt9e/lIwc2YBOAZusMCg==</inverseq><d>HTAvSnyJdSu/N2txpcZbvmbe4JvCgqcmcpSealHqpxGziV3W1rZI3O/UeATb1nZD6A0JsO/l0LWz6XM7+gHE0/jkq6LTjvLlN0ob4VtrslGmMJ6ISbiaGq4tL/rsOl3bRRJVc4bNEqDH6IgeUdRjgDe3ZVZeYzsVNHK8KYBWogk=</d></rsakeyvalue>" RSA.FromXmlString(publicprivatekeyxml) Dim decryptedKey As Byte() = RSA.Decrypt(getencryptedkey, False) pwd = System.Text.ASCIIEncoding.Unicode.GetString(decryptedKey) Dim dk As Byte() = Nothing Dim div As Byte() = Nothing crm.getKeysFromPassword(pwd, dk, div) cryptoKey = dk cryptoIV = div '#End Region Dim ext As String = Path.GetExtension(encName).ToLower() If ext <> ".enc" Then ' MessageBox.Show("Please Enter correct File"); Return End If Dim dncName As String = Path.GetDirectoryName(encName) & "\" & Path.GetFileNameWithoutExtension(encName) dncName = originalPath & "\Decrypted.dnc" Try If crm.DecryptData(encName, dncName, cryptoKey, cryptoIV) Then Dim fi As New FileInfo(encName) Dim fi2 As New FileInfo(dncName) If (fi.Attributes And FileAttributes.[ReadOnly]) = FileAttributes.[ReadOnly] Then fi.Attributes = fi.Attributes And Not FileAttributes.[ReadOnly] End If 'copy creation and modification time fi2.CreationTime = fi.CreationTime fi2.LastWriteTime = fi.LastWriteTime 'delete encrypted file ' MessageBox.Show("File Decrypted"); File.Delete(encName) ' MessageBox.Show("The file can't be decrypted - probably wrong password"); Else End If 'MessageBox.Show(ex.Message); Catch ex As CryptographicException ' MessageBox.Show(ex.Message); Catch ex As IOException 'i.e. readonly ' MessageBox.Show(ex.Message); Catch ex As UnauthorizedAccessException End Try 'MessageBox.Show(ex.Message); Catch ex As Exception End Try End Sub Public Function ReadEncryptFileToBuffer(ByVal fileSource As String) As String Const PROVIDER_RSA_FULL As Integer = 1 Const CONTAINER_NAME As String = "KeyContainer" Dim cspParams As CspParameters cspParams = New CspParameters(PROVIDER_RSA_FULL) cspParams.KeyContainerName = CONTAINER_NAME cspParams.Flags = CspProviderFlags.UseMachineKeyStore cspParams.ProviderName = "Microsoft Strong Cryptographic Provider" Dim buffer As String = "" testHeader = System.Text.Encoding.ASCII.GetBytes("testing header") testHeaderString = BitConverter.ToString(testHeader) Dim originalPath As String = fileSource.Substring(0, fileSource.LastIndexOf("\")) Dim alldata As Byte() = File.ReadAllBytes(fileSource) Dim getencryptedkey As Byte() = New Byte(127) {} Dim data As Byte() = New Byte(alldata.Length - 129) {} Try Dim current As DateTime = DateTime.Now Dim encName As String = fileSource & "data" & ".enc" Dim RSA As New RSACryptoServiceProvider(cspParams) For k As Integer = 0 To alldata.Length - 129 data(k) = alldata(k) Next Dim i As Integer = alldata.Length - 128, j As Integer = 0 While i < alldata.Length getencryptedkey(j) = alldata(i) i += 1 j += 1 End While Using bw As New BinaryWriter(File.Create(encName)) bw.Write(data) bw.Close() End Using Dim publicprivatekeyxml As String = "<rsakeyvalue><modulus>qwJYZm7ECFuktmofbVkm4J1kRf/L9521P70DaJhw/JNCwmCVItuaGEZWUlPZoMB6Q05Da7yYhkhVTHbybyxTcSMeQBsXb8jVqm3HWN3Quy8XITjGkuCsP8AijmXVV2RWa8T1oklN5SZfdaprue0ZWLjUFcZff5eay4igWjXpmVE=</modulus><exponent>AQAB</exponent><p>6RxsBsub9tG0hwRS92vLjxUuBF5adjifmLvB3cr1RnwcgX7EoVWiw/UPBzfiF/B9ZYkvu5EnL3ZTZ0Uae0eDrw==</p><q>u8zniy7nrMDyZHgnMR1yaL/w/bw0jPelo9t3h/1yOetFBRDYKGQQc3njLl/I8NIm0grug+x43vSOprh65m7y/w==</q><dp>ooqX5JEaehq1FyPzuePm9yjcgl1MFHzdA8F/p2g6aGBn+/9pmdk9egeo5+6WbvzYYvEqYE4RFa4a77omgelWrw==</dp><dq>lcTGjzgb6KiDZl5wGvo56JHSNfhnDFjfTzrSK7CS7N/UzkJtsGCEwiLda3lV/cAK142CQ9FNX7k3HnyW/rhSrw==</dq><inverseq>qni6yLGiI0ZsSabZutS+OI+qF8paE4+CMBQxj6BOt/35msm+L8kc+sqgsghy/MoZDnlt9e/lIwc2YBOAZusMCg==</inverseq><d>HTAvSnyJdSu/N2txpcZbvmbe4JvCgqcmcpSealHqpxGziV3W1rZI3O/UeATb1nZD6A0JsO/l0LWz6XM7+gHE0/jkq6LTjvLlN0ob4VtrslGmMJ6ISbiaGq4tL/rsOl3bRRJVc4bNEqDH6IgeUdRjgDe3ZVZeYzsVNHK8KYBWogk=</d></rsakeyvalue>" RSA.FromXmlString(publicprivatekeyxml) Dim decryptedKey As Byte() = RSA.Decrypt(getencryptedkey, False) pwd = System.Text.ASCIIEncoding.Unicode.GetString(decryptedKey) Dim dk As Byte() = Nothing Dim div As Byte() = Nothing crm.getKeysFromPassword(pwd, dk, div) cryptoKey = dk cryptoIV = div File.Delete(encName) Dim ext As String = Path.GetExtension(encName).ToLower() If ext <> ".enc" Then ' MessageBox.Show("Please Enter correct File"); Return "" End If Catch End Try Dim RijndaelCipher As RijndaelManaged Dim cryptoStream As CryptoStream = Nothing Dim memoryStream As MemoryStream = Nothing Dim fsIn As FileStream = Nothing Dim reader As StreamReader = Nothing, cryptoStreamReader As StreamReader = Nothing Dim decryptText As [String] = Nothing Try RijndaelCipher = New RijndaelManaged() RijndaelCipher.Mode = CipherMode.CBC RijndaelCipher.KeySize = 256 RijndaelCipher.BlockSize = 128 RijndaelCipher.Padding = PaddingMode.PKCS7 fsIn = New FileStream(fileSource, FileMode.Open, FileAccess.Read) reader = New StreamReader(fsIn, Encoding.[Default]) Dim cipherText As [String] = reader.ReadToEnd() Dim cipherByte As Byte() = System.Text.Encoding.[Default].GetBytes(cipherText) Dim decryptor As ICryptoTransform = RijndaelCipher.CreateDecryptor(cryptoKey, cryptoIV) memoryStream = New MemoryStream(data) cryptoStream = New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read) cryptoStreamReader = New StreamReader(cryptoStream) decryptText = cryptoStreamReader.ReadToEnd() buffer = decryptText.Substring(14) Return buffer Catch ex As FileNotFoundException If ex.FileName.CompareTo(fileSource) = 0 AndAlso Log.logPermission = True Then Dim writer As New StreamWriter(Log.logFileLocation) writer.WriteLine(ex.Message & " i.e. Input file for decryption Buffer") writer.Close() End If Catch ex As Exception If Log.logPermission = True Then Dim writer As New StreamWriter(Log.logFileLocation) writer.WriteLine(ex.Message & "i.e. During Reading Encrypted File to Decrypted Buffer") writer.Close() End If Finally If reader IsNot Nothing Then reader.Close() End If If cryptoStreamReader IsNot Nothing Then cryptoStreamReader.Close() End If If cryptoStream IsNot Nothing Then cryptoStream.Close() End If If memoryStream IsNot Nothing Then memoryStream.Close() End If If fsIn IsNot Nothing Then fsIn.Close() End If End Try buffer = decryptText Return buffer End Function Public Sub BufferToEncryptFile(ByVal buffer As String, ByVal folderPath As String) 'sunil code Const PROVIDER_RSA_FULL As Integer = 1 Const CONTAINER_NAME As String = "KeyContainer" Dim cspParams As CspParameters cspParams = New CspParameters(PROVIDER_RSA_FULL) cspParams.KeyContainerName = CONTAINER_NAME cspParams.Flags = CspProviderFlags.UseMachineKeyStore cspParams.ProviderName = "Microsoft Strong Cryptographic Provider" getPassword() Dim originalPath As String = folderPath Try Dim current As DateTime = DateTime.Now Dim RSA As New RSACryptoServiceProvider(cspParams) Dim keyToEncrypt As Byte() Dim encryptedKey As Byte() Dim origName As String = folderPath Dim encName As String = origName & ".enc" Try crm.EncryptBuffer(buffer, originalPath & "\EncodedBuffer.enc", cryptoKey, cryptoIV) Dim data As Byte() = File.ReadAllBytes(originalPath & "\EncodedBuffer.enc") 'delete original file File.Delete(originalPath & "\EncodedBuffer.enc") Dim publicprivatexml As String = RSA.ToXmlString(True) keyToEncrypt = System.Text.ASCIIEncoding.Unicode.GetBytes(pwd) encryptedKey = RSA.Encrypt(keyToEncrypt, False) Using bw As New BinaryWriter(File.Create(originalPath & "\Encrypted.enc")) 'Write data bw.Seek(0, SeekOrigin.Begin) bw.Write(data) bw.Write(encryptedKey) bw.Close() End Using Catch ex As CryptographicException Catch ex As IOException Catch ex As UnauthorizedAccessException End Try Catch ex As Exception End Try End Sub End Class End Namespace
Kenneth Haugland
Как это правильно сказать, мотыга-это нечто совершенно другое, для чего вы хотите получить здесь помощь.
Joan M
VB.NET по сравнению с VB6 они довольно похожи, и зная, что нет никаких инструментов для автоматического внесения изменений, вам придется делать это вручную.
Здесь не так много линий, так что давай!