Please how can i return decoded bytes instead of text from a CryptoStream

守給你的承諾、 提交于 2019-12-13 08:53:45

问题


Please how can i return the decoded bytes instead of text in the following snippet:

Public Shared Function decryptAsText(key As Byte(), ciphertext As Byte(), iv As Byte()) As String
    Dim dec As String = Nothing
    Try
        Using rj = New Security.Cryptography.RijndaelManaged With {.Key = key, .IV = iv, .Mode = Security.Cryptography.CipherMode.CBC, .Padding = PaddingMode.PKCS7}
            Using ms = New IO.MemoryStream(ciphertext)
                Using cs = New Security.Cryptography.CryptoStream(ms, rj.CreateDecryptor(key, iv), Security.Cryptography.CryptoStreamMode.Read)
                    Using sr = New IO.StreamReader(cs)
                        dec = sr.ReadToEnd
                    End Using
                End Using
            End Using
        End Using
    Catch e As Exception
    End Try

    Return dec
End Function

My attempt below fails

 Public Shared Function decryptAsBytes(key As Byte(), ciphertext As Byte(), iv As Byte()) As Byte()
        Try
            Using rj = New Security.Cryptography.RijndaelManaged With {.Key = key, .IV = iv, .Mode = Security.Cryptography.CipherMode.CBC, .Padding = PaddingMode.PKCS7}
                Using ms = New IO.MemoryStream(ciphertext)
                    Using cs = New Security.Cryptography.CryptoStream(ms, rj.CreateDecryptor(key, iv), Security.Cryptography.CryptoStreamMode.Read)
                        Dim l As Integer = CInt(cs.Length)
                        Dim b(l - 1) As Byte
                        cs.Read(b, 0, l)
                        Return b
                    End Using
                End Using
            End Using
        Catch e As Exception
        End Try
        Return {}
    End Function

回答1:


Finally got this to work

Public Shared Function decryptAsBytes(key As Byte(), ciphertext As Byte(), iv As Byte()) As Byte()
    Try
        Using rj = New Security.Cryptography.RijndaelManaged With {.Key = key, .IV = iv, .Mode = Security.Cryptography.CipherMode.CBC, .Padding = PaddingMode.PKCS7}
            Using ms = New IO.MemoryStream(ciphertext)
                Using cs = New Security.Cryptography.CryptoStream(ms, rj.CreateDecryptor(key, iv), Security.Cryptography.CryptoStreamMode.Read)
                    Using ds = New IO.MemoryStream()
                        cs.CopyTo(ds)
                        Return ds.ToArray
                    End Using
                End Using
            End Using
        End Using
    Catch e As Exception
    End Try
    Return {}
End Function


来源:https://stackoverflow.com/questions/30435607/please-how-can-i-return-decoded-bytes-instead-of-text-from-a-cryptostream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!