RC2加密! [英] RC2 encryption!

查看:123
本文介绍了RC2加密!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用RC2创建文件加密器.我不知道问题出在什么地方,但是当我加密文件时,我没有收到任何错误消息,但是当输出文件出来时,它是空白的!零字节!

我做错了什么?



Hi i''m trying to make a file encrypter with RC2. I don''t know what the problem is but when I encrypt a file I get no error messages but when the output file comes out it''s blank! zero bytes!

What am I doing wrong?



#Region "1. Global Variables "
 
    '*************************
    '** Global Variables
    '*************************

    Dim strFileToEncrypt As String
    Dim strFileToDecrypt As String
    Dim strOutputEncrypt As String
    Dim strOutputDecrypt As String
    Dim fsInput As System.IO.FileStream
    Dim fsOutput As System.IO.FileStream

#End Region


#Region "2. Create A Key "
 
    '*************************
    '** Create A Key
    '*************************

    Private Function CreateKey(ByVal Password As String) As Byte()
        'Convert strPassword to an array and store in chrData.
        Dim chrData() As Char = Password.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.
    End Function

#End Region


#Region "3. Create An IV "
 
    '*************************
    '** Create An IV
    '*************************

    Private Function CreateIV(ByVal Password As String) As Byte()
        'Convert strPassword to an array and store in chrData.
        Dim chrData() As Char = Password.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
    End Function

#End Region


#Region "4. Encrypt / Decrypt File "
 
    Public Sub DecryptFile(ByVal InputFile As String, ByVal OutputFile As String, ByVal Password As string, Optional ByVal DeleteUnencryptedFile As Boolean = False)
        Try 'In case of errors.

            'Setup file streams to handle input and output.
            fsInput = New System.IO.FileStream(InputFile, FileMode.Open, _
                                               FileAccess.Read)
            fsOutput = New System.IO.FileStream(OutputFile, 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 Rijndael As New System.Security.Cryptography.RC2CryptoServiceProvider

            csCryptoStream = New CryptoStream(fsOutput, _
            Rijndael.CreateDecryptor(createkey(Password), createIV(password), _
            CryptoStreamMode.Write)

            '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
            End While

            'Close FileStreams and CryptoStream.
            csCryptoStream.Close()
            fsInput.Close()
            fsOutput.Close()


            If DeleteUnencryptedFile = True Then
                'If decrypting then delete the encrypted file.
                Dim fileEncrypted As New FileInfo(InputFile)
                fileEncrypted.Delete()
            End If
            'Update the user when the file is done.
            Dim Wrap As String = Chr(13) + Chr(10)



            'Catch file not found error.
        Catch When Err.Number = 53 'if file not found
            MsgBox("Please check to make sure the path and filename" + _
                    "are correct and if the file exists.", _
                     MsgBoxStyle.Exclamation, "Invalid Path or Filename")

            'Catch all other errors. And delete partial files.
        Catch
            fsInput.Close()
            fsOutput.Close()

            Dim fileDelete As New FileInfo(OutputFile)
            fileDelete.Delete()

            MsgBox("Please check to make sure that you entered the correct " + _
                    "password.", MsgBoxStyle.Critical, "Invalid Password")

        End Try
    End Sub

    Public Sub EncryptFile(ByVal InputFile As String, _
                                         ByVal OutputFile As String, _
                                     ByVal Password As string , Optional ByVal DeleteEncryptedFile As Boolean = False)
        Try 'In case of errors.

            'Setup file streams to handle input and output.
            fsInput = New System.IO.FileStream(InputFile, FileMode.Open, _
                                               FileAccess.Read)
            fsOutput = New System.IO.FileStream(OutputFile, 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 Rijndael As New System.Security.Cryptography.RC2CryptoServiceProvider

            csCryptoStream = New CryptoStream(fsOutput, _
            Rijndael.CreateEncryptorcreatekey(Password), createIV(password)), _
            CryptoStreamMode.Write)



            '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
            End While

            'Close FileStreams and CryptoStream.
            csCryptoStream.Close()
            fsInput.Close()
            fsOutput.Close()

            'If encrypting then delete the original unencrypted file.
            If DeleteEncryptedFile = True Then
                Dim fileOriginal As New FileInfo(InputFile)
                fileOriginal.Delete()
            End If

            'Update the user when the file is done.
            Dim Wrap As String = Chr(13) + Chr(10)

            'Catch file not found error.
        Catch When Err.Number = 53 'if file not found
            MsgBox("Please check to make sure the path and filename" + _
                    "are correct and if the file exists.", _
                     MsgBoxStyle.Exclamation, "Invalid Path or Filename")

            'Catch all other errors. And delete partial files.
        Catch
            fsInput.Close()
            fsOutput.Close()

        End Try
    End Sub

#End Region



[修改:只是将它放下,所以它不受投票箱的限制]



[Modified: just moved it down so it wasn''t constrained by the voting box]

推荐答案

找到了另一个错字……至少我希望它是一个错字错别字:

found another typo...at least I hope it''s a typo:

'If encrypting then delete the original unencrypted file.
If DeleteEncryptedFile = True Then


在加密方法中.

除了这两种错别字外,您发布的代码还不错,所以唯一的问题就是传递给方法的内容.


within the encrypt method.

Aside from the two typos, the code you posted is fine, so the only problem would be with what you were passing into the methods.


这是一个基本问题,但是您是否逐步完成了代码?

而且,希望将代码转移到此处时出现输入错误,但是
This is a basic question, but did you step through the code?

And, I hope it''s a typing error when transferring the code into here but
Rijndael.CreateEncryptorcreatekey(Password), createIV(password))


无法工作,因为您在CreateEncryptor之后缺少了一个(.

还有一个提示...但是由于您没有使用Rijndael代码,因此应将对象的名称更改为实际将其标识为RC2的名称.

逐步检查csCryptoStream是否正确创建.由于创建它是您实际上更改了CP文章中的代码的唯一位置,因此我将首先查看.我知道其余代码可与Rijndael一起使用,因为我在程序中使用了它.


won''t work because you''re missing a ( after CreateEncryptor.

And a hint...but since you''re not using a Rijndael code, you should change the name of the object to something that actually identifies it as an RC2.

Step through and see if the csCryptoStream is created correctly. Since the creation of it is the only place that you''ve actually changed the code from the CP article, I would look there first. I know that the rest of the code works with Rijndael because I use it in a program.


这篇关于RC2加密!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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