如何将vb.net转换为vb6 [英] How to convert vb.net to vb6

查看:484
本文介绍了如何将vb.net转换为vb6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在c#和vb.net中编写了代码,但现在要求是vb6.Can我将vb.net代码转换为vb6。如何在vb6中添加命名空间System.Security.Cryptography

< pre lang =vb> Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Security.Cryptography
< span class =code-keyword> Imports System.IO

命名空间 RijndaelEncDec

< span class =code-keyword>公共 枚举 CryptoEventType

消息

FileProgress

结束 枚举

公共 CryptoEventArgs
继承 EventArgs

私有 m_type 作为 CryptoEventType

私有 m_message 作为 字符串

私有 m_fileLength 作为 整数

私有 m_filePosition 作为 整数

公共 Sub ByVal 消息作为 字符串

m_type = CryptoEventType.Message


.m_message =信息
结束 Sub

公开 Sub ByVal fileName 作为 字符串 ByVal fileLength 作为 整数 ByVal filePosition 作为 整数

m_type = CryptoEventType.FileProgress

.m_fileLength = fileLength

.m_filePosition = filePosition


m_message = fileName
结束 Sub

公共 ReadOnly 属性类型( ) As CryptoEventType

获取
返回 m_type
结束 获取
结束 属性


公开 ReadOnly 属性消息() As 字符串

获取
返回 m_message
结束 获取
<跨度class =code-keyword>结束 属性


公开 ReadOnly 属性 FileName() As 字符串

获取
返回 m_message
结束 获取
< span class =code-keyword>结束 属性


公共 ReadOnly 属性 FileLength() As 整数

获取
返回 m_fileLength
结束 获取
结束 属性


公共 ReadOnly 属性 FilePosition() As 整数

获取
返回 m_filePosition
结束 获取
结束 属性


结束 < span class =code-keyword> Class


Public Delegate Sub cryptoEventHandler( ByVal sender As Object ByVal e As CryptoEventArgs)

''' < summary >

'''

''' < / summary >

公共 CryptoManager

私人 testHeader 作为 字节()= 没什么
' 用于验证解密是否成功
私有 testHeaderString 作为 字符串 = 没有什么

公共 Sub ()

testHeader = System.Text.Encoding.ASCII.GetBytes( 测试标题


testHeaderString = BitConverter.ToString(testHeader)
结束 < span class =code-keyword> Sub
公共 Sub getKeysFr omPassword( ByVal 传递作为 字符串,< span class =code-keyword> ByRef rijnKey As Byte (), ByRef rijnIV 作为 字节())

Dim salt 作为 字节()= System.Text.Encoding.ASCII.GetBytes( System.Text.Encoding.ASCII.GetBytes

Dim pb As PasswordDeriveBytes(pass,salt)

rijnKey = pb.GetBytes( 32

rijnIV = pb.GetBytes( 16

结束 Sub

< span class =code-keyword> Const bufLen 作为 整数 = 4096

公共 Sub EncryptData ( ByVal inName 作为 [ String ], ByVal outName 作为 [字符串],< span class =code-keyword> ByVal rijnKey As Byte (), ByVal rijnIV 作为 字节())

Dim fin As FileStream = Nothing

Dim fout As FileStream = Nothing

Dim encStream As CryptoStream = Nothing

尝试

' 创建文件流来处理输入和输出文件。

fin = FileStream(inName,FileMode.Open,FileAccess.Read)

fout = FileStream(outName,FileMode.Create,FileAccess.Write)

' 创建变量以帮助读写。

Dim bin 作为 字节 ()= 字节(bufLen - 1 ){}
' 这是加密的中间存储。
< span class =code-keyword> Dim rdlen 作为 = 0
' 这是写入的总字节数。
Dim totlen As Long = fin.Length
' 这是输入文件的总长度。
Dim len 作为 整数
' 这是一次要写入的字节数。
Dim rijn 作为 RijndaelManaged ()

rijn.Mode = CipherMode.CBC
rijn.KeySize = 256
rijn.BlockSize = 128
rijn.Padding = PaddingMode.PKCS7

encStream = CryptoStream (fout,rijn.CreateEncryptor(rijnKey,rijnIV),CryptoStreamMode.Write)

' zakoduj testowy片段

encStream.Write(testHeader, 0 ,testHeader.Length)

' < span class =code-comment>从输入文件中读取,然后加密并写入输出文件。

while True

len = fin.Read(bin, 0 ,bufLen)

如果 len = 0 然后

退出
结束 如果

encStream.Write(bin, 0 ,len)



rdlen + = len


< span class =code-keyword>结束
最后


如果 encStream IsNot 没什么 然后

encStream.Close()
结束 如果

如果 fout IsNot Nothing 然后

fout.Close()
结束 如果

如果 fin IsNot Nothing 然后< /跨度>

fin.Close()

结束 如果
结束 尝试

结束 Sub

公开 Sub EncryptBuffer( ByVal buffer As [ String ], ByVal outName As [ String ], ByVal rijnKey 作为 字节(), ByVal rijnIV 作为 字节())

Dim fin As FileStream = Nothing

< span class =code-keyword> Dim
fout As FileStream = Nothing

Dim encStream As CryptoStream = Nothing

尝试

' < span class =code-comment>创建文件流来处理输入和输出文件。

' fin = new FileStream((inName,FileMode.Open,FileAccess.Read);
Dim byteArray < span class =code-keyword> As Byte ()= Encoding.ASCII.GetBytes(buffer)

Dim mem 作为 MemoryStream(byteArray)

fout = FileStream(outName,FileMode.Create,FileAccess.Write)

' 创建变量以帮助读写。

Dim bin As Byte ()= 字节(bufLen - 1 ){}
' 这是加密的中间存储。
Dim rdlen As Long = 0
' 这是写入的总字节数。
Dim totlen 作为 = mem.Length
' 这是输入文件的总长度。
Dim len 作为 整数
' 这是一次要写入的字节数。
Dim rijn 作为 RijndaelManaged( )

rijn.Mode = CipherMode.CBC
rijn.KeySize = 256
rijn.BlockSize = 128
rijn.Padding = PaddingMode.PKCS7

encStream = CryptoStream(fout,rijn.CreateEncryptor(rijnKey,rijnIV),CryptoStreamMode.Write)

' zakoduj testowy片段

encStream.Write(testHeader, 0 ,testHeader.Length)

' 从输入文件中读取,然后加密并写入输出文件。

True

len = mem.Read(bin, 0 ,bufLen)

如果 len = 0 然后

退出 虽然
结束 如果

encStream.Write (bin, 0 ,len)



rdlen + = len


结束
最后


如果 encStream IsNot Nothing 然后

encStream.Close()
结束 如果

如果 fout IsNot 没什么 然后

fout.Close()
结束 如果

如果 fin IsNot Nothing 然后

fin.Close()

结束 如果
结束 尝试

结束 Sub

公开 功能 DecryptData( ByVal inName As [字符串], ByVal outName As [ String ], ByVal rijnKey 作为 字节(), ByVal rijnIV 作为 字节()) As Boolean

' 创建文件流以处理输入和输出文件。

Dim fin As FileStream = Nothing

Dim fout As FileStream = Nothing

Dim decStream As CryptoStream = Nothing

尝试

fin = FileStream(inName,FileMode.Open,FileAccess.Read)

' 创建变量以帮助读写。

Dim bin 作为 字节()= < span class =code-keyword>新
字节(bufLen - 1 ){}
' 这是加密的中间存储。
Dim rdlen 作为 = 0
' 这是写入的总字节数。
Dim totlen 作为 = fin.Length
' 这是输入文件的总长度。
Dim len 作为 整数
' 这是一次要写入的字节数。
Dim rijn 作为 RijndaelManaged( )

rijn.Mode = CipherMode.CBC
rijn.KeySize = 256
rijn.BlockSize = 128
rijn.Padding = PaddingMode.PKCS7
DES ds = new DESCryptoServiceProvider();

decStream = CryptoStream(fin,rijn.CreateDecryptor(rijnKey,rijnIV),CryptoStreamMode.Read)


' odkoduj testowy片段

Dim test 作为 字节()= 字节(testHeader.Length - 1 ){}

decStream.Read(test, 0 ,testHeader.Length)

I f BitConverter.ToString(test)<> testHeaderString 然后

decStream.Clear()

decStream = 没什么


返回 错误
结束 如果

' 创建输出文件

fout = FileStream(outName,FileMode) .Create,FileAccess.Write)

' 从加密文件中读取并写入dercypted数据

True

len = decStream.Read(bin, 0 ,bufLen )

如果 len = 0 然后

退出
结束 如果

fout.Write(bin, 0 ,len)



rdlen + = len
结束 < span class =code-keyword> while



返回 True
最后


如果 decStream IsNot Nothing 那么

decStream.Close()
结束 如果

如果 fout IsNot Nothing 然后

fout.Close()
结束 如果

如果 fin IsNot Nothing 然后

fin.Close()

结束 如果
结束 尝试

结束 功能

结束


公开 日志
公开 共享 logPermission 作为 布尔 = True
公共 共享 logFileLocation As [字符串] = D:\\ \\ C#EncDecLogFile.txt

结束

公开 Rijndael
私人 pwd 作为 字符串 =

私有 testHeader 作为 字节 ()= 没什么
' 用于验证如果解密成功
私有 testHeaderString 作为 字符串 =

私有 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 curren t 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() + curre nt.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/JNCwmCVItuaGEZWUlPZoMB6Q05Da7yYhkhVTH bybyxTcSMeQBsXb8jVqm3HWN3Quy8XITjGkuCsP8AijmXVV2RWa8T1oklN5SZfdaprue0ZWLjUFcZff5eay4igWjXpmVE=</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 C ryptographic 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/JNCwmCVItuaGEZWUlPZoMB6Q05Da7yYhkhVTHb ybyxTcSMeQBsXb8jVqm3HWN3Quy8XITjGkuCsP8AijmXVV2RWa8T1oklN5SZfdaprue0ZWLjUFcZff5eay4igWjXpmVE=</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 = Pat h.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 memoryStr eam 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.CreateDecrypt or(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 cspPara ms 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

解决方案

You have to rewrite by hand. There is no conversion tool to go backwards, there are no namespaces in VB6 and you better know VB6 and your .NET code inside and out.



You’re going to be doing a ton of PInvoking of Win32 functions in VB6 to rewrite this code.



No, nobody is going to do this for you and frankly, using VB6 is not a \"requirement\". It’s incredibly stupid in this day and age to do any new development in VB6 as VB6 has been officially dead for quite a number of years now.


I have written code in c# and vb.net but now the requirement is vb6.Can i convert vb.net code to vb6.How to add namespace in vb6 System.Security.Cryptography

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

解决方案

You have to rewrite by hand. There is no conversion tool to go backwards, there are no namespaces in VB6 and you better know VB6 and your .NET code inside and out.

You're going to be doing a ton of PInvoking of Win32 functions in VB6 to rewrite this code.

No, nobody is going to do this for you and frankly, using VB6 is not a "requirement". It's incredibly stupid in this day and age to do any new development in VB6 as VB6 has been officially dead for quite a number of years now.


这篇关于如何将vb.net转换为vb6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆