解密加密文本文件内容并将其复制到MemoryStream

Sim*_*ose 1 vb.net encryption des tripledes

我试图将文本文件的加密内容复制到内存流中,然后解密这些内容并将其复制到新的内存流中。当我到达发生复制的代码时,我在调试时收到无效数据错误。

这是我得到的代码块:

Function DecryptFile(ByVal sInputFilename As String, ByVal sKey As String) As Byte()

    Dim DES As New DESCryptoServiceProvider()

    DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)

    Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor()

    Dim encryptedByteArray() As Byte
    encryptedByteArray = File.ReadAllBytes(sInputFilename)

    Dim encryptedMS As MemoryStream = New MemoryStream(encryptedByteArray)
    Dim cryptostreamDecr As New CryptoStream(encryptedMS, desdecrypt, CryptoStreamMode.Read)
    Dim decryptedMS As MemoryStream = New MemoryStream()

    cryptostreamDecr.CopyTo(decryptedMS) 'Error occurs here
    cryptostreamDecr.Close()

    Return decryptedMS.ToArray()
End Function
Run Code Online (Sandbox Code Playgroud)

我正在关注散布在网络上的示例,从我读过的内容来看,这段代码应该可以工作......

谁能向我解释我做错了什么?

Jim*_*imi 5

这是一个使用密钥加密/解密字符串和文件而不显式提供初始化向量的示例(因此您不需要存储和检索它来解密加密数据)。

我在这里使用的加密提供程序是TripleDESCryptoServiceProvider
如果您需要使用 DES 提供程序,则完全相同,您只需要更改TripleDESCryptoServiceProviderDESCryptoServiceProvider 即可
但是,正如您在 Docs 中所读到的,如果可能的话,最好转向AesCryptoServiceProvider

初始化向量 ( IV) 是根据指定的密钥计算的,如果解密数据的密钥与用于加密数据的密钥相同,则它是相同的哈希值。

在这种情况下,您失去了一些安全性,但您不需要存储密钥或IV(如果密钥由负责保护密钥的用户提供)。

模式是留给它的默认:CipherMode.CBC
填充模式为它的默认:PaddingMode.PKCS7


加密和解密来自 Base64String 的字符串:

Dim enc3Des As New TripleDesEncryptor("MyFancyKey")

Dim inputString = "Some fancy string to be encoded to a Base64 string"
Dim encodedB64 = enc3Des.EncryptStringToBase64(inputString)
Dim decoded64 = enc3Des.DecryptBase64String(encoded64)
Run Code Online (Sandbox Code Playgroud)

要加密文件,请提供源文件的路径,然后将 Encryption 方法返回的字节保存到目标文件:

Dim enc3Des As New TripleDesEncryptor("MyFancyKey")

Dim plainTextFilePath = [Source file Path]
Dim encryptedFilePath = [Encrypted file Path]

Dim encodedBytes = enc3Des.EncryptFile(plainTextFilePath)
File.WriteAllBytes(encryptedFilePath, encodedBytes)
Run Code Online (Sandbox Code Playgroud)

您当然可以在需要时使用相同的密钥解密文件:

Dim encryptedFilePath = [Encrypted file Path]
Dim decryptedFilePath = [Decrypted file Path]

Dim enc3Des2 As New TripleDesEncryptor("MyFancyKey")

Dim decodedBytes = enc3Des2.DecryptFile(encryptedFilePath)
File.WriteAllBytes(decryptedFilePath, decodedBytes)
Run Code Online (Sandbox Code Playgroud)

TripleDesEncryptor辅助类:

Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Public NotInheritable Class TripleDesEncryptor

    Private tripleDesProvider As New TripleDESCryptoServiceProvider()

    Sub New(key As String)
        tripleDesProvider.Key = GetKeyHash(key, tripleDesProvider.LegalKeySizes(0).MaxSize \ 8)
        tripleDesProvider.IV = GetKeyHash(key, tripleDesProvider.LegalBlockSizes(0).MaxSize \ 8)
    End Sub

    Public Function EncryptStringToBase64(inputString As String) As String
        Dim dataBytes As Byte() = Encoding.Unicode.GetBytes(inputString)
        Return Convert.ToBase64String(Encrypt(dataBytes))
    End Function

    Public Function EncryptFile(fileName As String) As Byte()
        Dim dataBytes As Byte() = File.ReadAllBytes(fileName)
        Return Encrypt(dataBytes)
    End Function

    Private Function Encrypt(dataBytes As Byte()) As Byte()
        Using ms As New MemoryStream(),
            encStream As New CryptoStream(ms, tripleDesProvider.CreateEncryptor(), CryptoStreamMode.Write)
            encStream.Write(dataBytes, 0, dataBytes.Length)
            encStream.FlushFinalBlock()
            Return ms.ToArray()
        End Using
    End Function

    Public Function DecryptBase64String(base64String As String) As String
        Dim dataBytes As Byte() = Convert.FromBase64String(base64String)
        Return Encoding.Unicode.GetString(Decrypt(dataBytes))
    End Function

    Public Function DecryptFile(fileName As String) As Byte()
        Dim dataBytes As Byte() = File.ReadAllBytes(fileName)
        Return Decrypt(dataBytes)
    End Function

    Private Function Decrypt(encryptedData As Byte()) As Byte()
        Using ms As New MemoryStream(),
            decStream As New CryptoStream(ms, tripleDesProvider.CreateDecryptor(), CryptoStreamMode.Write)
            decStream.Write(encryptedData, 0, encryptedData.Length)
            decStream.FlushFinalBlock()
            Return ms.ToArray()
        End Using
    End Function

    Private Function GetKeyHash(key As String, length As Integer) As Byte()
        Using sha1 As New SHA1CryptoServiceProvider()
            Dim varHash As Byte() = New Byte(length - 1) {}
            Dim keyBytes As Byte() = Encoding.Unicode.GetBytes(key)
            Dim hash As Byte() = sha1.ComputeHash(keyBytes).Take(length).ToArray()
            Array.Copy(hash, 0, varHash, 0, hash.Length)
            hash = Nothing
            keyBytes = Nothing
            Return varHash
        End Using
    End Function
End Class
Run Code Online (Sandbox Code Playgroud)