Update:
I made some edits to clean up remnants of efforts that weren't helping.
I understood previously that "something" is occurring during the file-write process and that it's something that I personally am not perceiving.
Thanks to Plutonix in the comments, I know that the problem is in how I'm handling this but I don't understand exactly how to do it properly and research isn't turning anything up.
I'm attempting to write a file that must be then prefixed with an md5 checksum of itself
The result should be
[hash of "the brown fox"]the brown fox
In the example file I'm testing on, this is the hash I want to reproduce. Viewing in UTF-8 or in Hex reveals that these are the only characters within
¶ Â趓Naþ¼Wô}¾}
VB.net Debug.print produces exactly this
Hash.tostring: ¶ Â趓Naþ¼Wô}¾}
hash.length: 16
hash.tostring.length: 16
utf8hash.length: 28 -- I think this is part of the problem?
The file writes, as seen in UTF-8 or a Hex Editor
¶ Â趓Naþ¼Wô}¾}
This is one variant of most of my efforts
Dim HashMaker As New MD5CryptoServiceProvider()
Dim HashBytes As Byte() = HashMaker.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()))
Dim Hash As New StringBuilder()
For hx = 0 To HashBytes.Length - 1
Hash.Append(Chr(HashBytes(hx)))
Next
Dim HashMaker As New MD5CryptoServiceProvider()
Dim HashBytes As Byte() = HashMaker.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()))
Dim Hash As New StringBuilder()
For hx = 0 To HashBytes.Length - 1
Hash.Append(Chr(HashBytes(hx)))
Next
Debug.Print(Hash.ToString())
Dim fHeader As Byte() = New Byte(7) {}
Array.Copy(b, fHeader, 8)
Dim utf8hash As Byte() = Encoding.UTF8.GetBytes(Hash.ToString())
System.IO.File.WriteAllText(fname & "_long", "")
Dim s As New System.IO.FileStream(fname & "_long", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite)
s.Write(b, 0, 8)
s.Write(utf8hash, 0, utf8hash.Length)
s.Write(Encoding.UTF8.GetBytes(sb.ToString()), 0, sb.Length)
s.Close()
I've tried an alternate method
Dim utf8 As String = ""
For hx = 0 To HashBytes.Length - 1
Hash.Append(Chr(HashBytes(hx)))
utf8 &= Chr(HashBytes(hx))
Next
Dim fHeader As Byte() = New Byte(7) {}
Array.Copy(b, fHeader, 8)
Dim utf8hash As Byte() = Encoding.UTF8.GetBytes(Hash.ToString())
Debug.Print("Hash.tostring: " & Hash.ToString())
Debug.Print("hash.length: " & Hash.Length)
Debug.Print("hash.tostring.length: " & Hash.ToString.Length)
Debug.Print("utf8hash.length: " & utf8.Length)
System.IO.File.WriteAllText(fname & "_long", "")
Dim s As New System.IO.FileStream(fname & "_long", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite)
s.Write(b, 0, 8)
s.Write(Encoding.UTF8.GetBytes(utf8), 0, 16)
s.Write(Encoding.UTF8.GetBytes(sb.ToString()), 0, sb.Length)
As for a Self-contained example:
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Security.Cryptography
Public Class Form1
Private Function TestWrite()
Dim book As Integer = 5, row As Integer = 5
Dim fname As String = "c:\programtestFile.dat"
Dim sb As New StringBuilder
Dim HashMaker As New MD5CryptoServiceProvider()
Dim HashBytes As Byte() = HashMaker.ComputeHash(Encoding.UTF8.GetBytes("test"))
Dim Hash As New StringBuilder()
For hx = 0 To HashBytes.Length - 1
Hash.Append(Chr(HashBytes(hx)))
Next
Debug.Print(Hash.ToString)
Dim utf8hash As Byte() = Encoding.UTF8.GetBytes(Hash.ToString())
System.IO.File.WriteAllText(fname & "_long", "")
Dim s As New System.IO.FileStream(fname & "_long", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite)
's.Write(b, 0, 8)
s.Write(utf8hash, 0, utf8hash.Length)
's.Write(Encoding.UTF8.GetBytes(sb.ToString()), 0, sb.Length)
s.Close()
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TestWrite()
End Sub
End Class
The code below prints this this to debug window
kÍF!ÓsÊÞNƒ&'´ö (it is prefixed by a tab, part of the computed hash)
But writes this to the file (as can be seen in a hex editor or setting the Encoding to UTF-8
ÂkÃF!ÓsÊÞNÆ’&'´ö
It turned out what I needed to do is assemble all the Bytes into a single Byte Array like so.
The first 8 bytes are a sort of header. The next 16 are an MD5 checksum of the remaining bytes.
I hope this helps someone.
Dim FileBytes(8 + HashBytes.Length + StringBytes.Length - 1) As Byte
Array.Copy(b, 0, FileBytes, 0, 8)
Array.Copy(HashBytes, 0, FileBytes, 8, 16)
Array.Copy(StringBytes, 0, FileBytes, 24, StringBytes.Length)
System.IO.File.WriteAllBytes(fname, FileBytes)
Related
I have had a hard time finding any support for Chrome Native Messaging Hosts in VB.Net, after much trial and error I have put together something that works for a single message at a time. However I have not been able to get the
While OpenStandardStreamIn() IsNot Nothing
part to work. If anyone has any suggestions...
OTHERWISE THIS CODE WORKS GREAT, for anyone else like me looking for a VB.Net Native Message Host:
Also, this uses Newtonsoft.Json Lib for JSON serializing...
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Module Module1
Public Sub Main(ByVal args As String())
'create response as an array so it can be easily converted JSON
Dim ResponseString() As String = {""}
' get input from chrome extension
Dim InputString As String = OpenStandardStreamIn()
' Do whatever you want with Input, then prepare Response
ResponseString(0) = DO_SOMETHING(InputString)
' Send Response to Chrome
OpenStandardStreamOut(ResponseString)
End Sub
Public Function OpenStandardStreamIn() As String
Dim MsgLength As Integer = 0
Dim InputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {} 'first 4 bytes are length
Dim StdIn As System.IO.Stream = Console.OpenStandardInput() 'open the stream
StdIn.Read(LenBytes, 0, 4) 'length
MsgLength = System.BitConverter.ToInt32(LenBytes, 0) 'convert length to Int
Dim Buffer As Char() = New Char(MsgLength - 1) {} 'create Char array for remaining bytes
Using Reader As System.IO.StreamReader = New System.IO.StreamReader(StdIn) 'Using to auto dispose of stream reader
While Reader.Peek() >= 0 'while the next byte is not Null
Reader.Read(Buffer, 0, Buffer.Length) 'add to the buffer
End While
End Using
InputData = New String(Buffer) 'convert buffer to string
Return InputData
End Function
Private Sub OpenStandardStreamOut(ByVal ResponseData() As String) 'fit the response in an array so it can be JSON'd
Dim OutputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {} 'byte array for length
Dim Buffer As Byte() 'byte array for msg
OutputData = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseData) 'convert the array to JSON
Buffer = System.Text.Encoding.UTF8.GetBytes(OutputData) 'convert the response to byte array
LenBytes = System.BitConverter.GetBytes(Buffer.Length) 'convert the length of response to byte array
Using StdOut As System.IO.Stream = Console.OpenStandardOutput() 'Using for easy disposal
StdOut.WriteByte(LenBytes(0)) 'send the length 1 byte at a time
StdOut.WriteByte(LenBytes(1))
StdOut.WriteByte(LenBytes(2))
StdOut.WriteByte(LenBytes(3))
For i As Integer = 0 To Buffer.Length - 1 'loop the response out byte at a time
StdOut.WriteByte(Buffer(i))
Next
End Using
End Sub
End Module
From the Chrome Extension, open a connection, send a message, and once a response is received the host will close. Check our Chrome's Dev page for a sample app/extension: https://developer.chrome.com/apps/nativeMessaging
I hope this helps somebody, and please let me know if you make any improvements!
Sub Main() ' Recursive Version
Try
Dim stdin As Stream = Console.OpenStandardInput()
Dim stdout As Stream = Console.OpenStandardOutput()
Dim MsgLength As Integer = 0
Dim InputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {}
stdin.Read(LenBytes, 0, 4)
MsgLength = BitConverter.ToInt32(LenBytes, 0)
Dim Buffer As Byte() = New Byte(MsgLength - 1) {}
stdin.Read(Buffer, 0, Buffer.Length)
InputData = Encoding.UTF8.GetString(Buffer)
Dim Str As String = Newtonsoft.Json.JsonConvert.SerializeObject("[" & Now & "] Arrrr!")
Dim buff() As Byte = Encoding.UTF8.GetBytes(Str)
stdout.Write(BitConverter.GetBytes(buff.Length), 0, 4)
stdout.Write(buff, 0, buff.Length)
Main()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Oh, Snap!")
End Try
End Sub
Im having this error on vb.net "unable to read beyond the end of the stream".
It happens when i compile the program and it breaks in there.
Dim red As Byte = br.ReadByte()
Dim green As Byte = br.ReadByte()
Dim blue As Byte = br.ReadByte()
Dim flags As Byte = br.ReadByte()
But i will also give all the code:
Public Shared Function LoadPal(filename As String) As List(Of Color)
Dim colors As New List(Of Color)()
Dim stream As New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)
Using br As New BinaryReader(stream)
' RIFF header
Dim riff As String = ReadByteString(br, 4)
' "RIFF"
Dim dataSize As Integer = br.ReadInt32()
Dim type As String = ReadByteString(br, 4)
' "PAL "
' Data chunk
Dim chunkType As String = ReadByteString(br, 4)
' "data"
Dim chunkSize As Integer = br.ReadInt32()
Dim palVersion As Short = br.ReadInt16()
' always 0x0300
Dim palEntries As Short = br.ReadInt16()
' Colors
For i As Integer = 0 To palEntries - 1
Dim red As Byte = br.ReadByte()
Dim green As Byte = br.ReadByte()
Dim blue As Byte = br.ReadByte()
Dim flags As Byte = br.ReadByte()
' always 0x00
colors.Add(Color.FromArgb(red, green, blue))
Next
End Using
Return colors
End Function
Private Shared Function ReadByteString(br As BinaryReader, length As Integer) As String
Return Encoding.ASCII.GetString(br.ReadBytes(length))
End Function
Another lucky man. I hope this help u, i dont know why but the pallets must load 2 by 2, if not the colors will get mixed or something like that.
To Call load
'''''''''''''''''''''''''''''''''
Dim colors1
colerss = LoadPal(.FileName)
'''''''''''''''''''''''''''''''''
'LOAD PALL
Public Shared Function LoadPal(filename As String) As List(Of Color)
Dim colors As New List(Of Color)()
Dim stream As New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)
Using br As New BinaryReader(stream)
' RIFF header
' Colors
For i As Integer = 0 To 7
Try
''''''''''''First''''''''''''''''
Dim red As Byte = br.ReadByte()
Dim green As Byte = br.ReadByte()
Dim blue As Byte = br.ReadByte()
Dim flags As Byte = br.ReadByte()
'MsgBox(blue & " " & green & " " & red)
colors.Add(Color.FromArgb(blue, green, red))
''''''''''''''''''Second''''''''''''''''''''
Dim red1 As Byte = br.ReadByte()
Dim green1 As Byte = br.ReadByte()
Dim blue1 As Byte = br.ReadByte()
Dim flags1 As Byte = br.ReadByte()
'MsgBox(blue1 & " " & green1 & " " & red1)
colors.Add(Color.FromArgb(blue1, green1, red1))
'''''''''''''''''''''''''''''''''''''''''''''''
Catch
MsgBox("Erro")
Finally
End Try
Next
End Using
Return colors
End Function
Private Shared Function ReadByteString(br As BinaryReader, length As Integer) As String
Return Encoding.ASCII.GetString(br.ReadBytes(length))
End Function
And why Load if u can Save?
To Call Save
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
SavePal(saveFileDialog1.FileName & "TheNameUWant.pal", colors1)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'SAVE PAL
Public Shared Sub SavePal(filename As String, colors As List(Of Color))
' Calculate file length
Dim stream As New FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None)
Using bw As New BinaryWriter(stream)
' Colors
For i = 0 To 15
'i dont know why but for writing the pallete the bytes are written in the reverse order
bw.Write(CByte(colors(i).B))
bw.Write(CByte(colors(i).G))
bw.Write(CByte(colors(i).R))
' Flag in W:A always 0x00
bw.Write(CByte(0))
Next
WriteStringBytes(bw, "PAL ")
End Using
End Sub
Private Shared Sub WriteStringBytes(bw As BinaryWriter, value As String)
bw.Write(Encoding.ASCII.GetBytes(value))
End Sub
Dim ShowImgWebClient = New WebClient
Dim ImageInBytes As Byte() = ShowImgWebClient.DownloadData("http://ex.domain.com/index.php?checksum=" & lblCheckSum.Text.ToString())
Dim ImageStream As New MemoryStream(ImageInBytes)
Dim CaptchaImg As Image = New Bitmap(ImageStream)
ptbCaptcha.Image = CaptchaImg
I'm use this code for get online captcha to my picturebox name ptbCaptcha.
but when request this image my program show error Parameter is not Valid.
Why this ? and How to make it work ?
This is not the proper way to use MemoryStream.
Here is the example taken from microsoft website :
Imports System
Imports System.IO
Imports System.Text
Module MemStream
Sub Main()
Dim count As Integer
Dim byteArray As Byte()
Dim charArray As Char()
Dim uniEncoding As New UnicodeEncoding()
' Create the data to write to the stream.
Dim firstString As Byte() = _
uniEncoding.GetBytes("Invalid file path characters are: ")
Dim secondString As Byte() = _
uniEncoding.GetBytes(Path.GetInvalidPathChars())
Dim memStream As New MemoryStream(100)
Try
' Write the first string to the stream.
memStream.Write(firstString, 0 , firstString.Length)
' Write the second string to the stream, byte by byte.
count = 0
While(count < secondString.Length)
memStream.WriteByte(secondString(count))
count += 1
End While
' Write the stream properties to the console.
Console.WriteLine( _
"Capacity = {0}, Length = {1}, Position = {2}", _
memStream.Capacity.ToString(), _
memStream.Length.ToString(), _
memStream.Position.ToString())
' Set the stream position to the beginning of the stream.
memStream.Seek(0, SeekOrigin.Begin)
' Read the first 20 bytes from the stream.
byteArray = _
New Byte(CType(memStream.Length, Integer)){}
count = memStream.Read(byteArray, 0, 20)
' Read the remaining Bytes, Byte by Byte.
While(count < memStream.Length)
byteArray(count) = _
Convert.ToByte(memStream.ReadByte())
count += 1
End While
' Decode the Byte array into a Char array
' and write it to the console.
charArray = _
New Char(uniEncoding.GetCharCount( _
byteArray, 0, count)){}
uniEncoding.GetDecoder().GetChars( _
byteArray, 0, count, charArray, 0)
Console.WriteLine(charArray)
Finally
memStream.Close()
End Try
End Sub
End Module
See MemoryStream for more information.
I am creating an application to create a key that is unique to each computer. This info is derived from the OS serial number and processorID.
Is there a way to 'shorten' a string? Maybe by converting it to HEX or something else...
The reason is this: I used to use a VB6 section of code (http://www.planet-source-code.com/vb...48926&lngWId=1) that gets the details and the output is only 13 digits long. Mine is a lot longer, but gets the same info...
BTW, the link I posted above won multiple awards, but I am having huge trouble in converting it to .NET. Has anyone by any chance converted it, or know of someone who has? Or a tool that actually works?
Thanks
EDIT
Here is the full working link: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48926&lngWId=1
It sounds like you want a 'hashing algorithm' or 'hash function'. They are a common concept: http://en.wikipedia.org/wiki/Hash_function
Generally speaking you can simply write your own function to take a string and return a hashed number but there is some suitable code here that uses the .NET framework: http://support.microsoft.com/kb/301053
Here is a working example which retrieves the Processor ID, for the first Processor found, and the OS Serial Number; it concatenates these to strings together and then performs various encodings on them.
This is a simple VB.Net Console project. Be sure to reference the System.Management assembly in your project. Just copy and paste this code example into the main module, set a breakpoint at the end of Sub Main(), and look at the various results.
Module Module1
Sub Main()
Dim uniqueID As String = GetUniqueID()
' convert it to a base64 string
Dim encoding As New Text.ASCIIEncoding()
Dim result1 = Convert.ToBase64String(encoding.GetBytes(uniqueID))
' compress it
Dim result2 As String = CompressString(uniqueID)
Dim result3 As String = DecompressString(result2)
' encrypt it
Dim result4 As String = AES_Encrypt(uniqueID, "password")
Dim result5 As String = AES_Decrypt(result4, "password")
' hash it
Dim result6 As String = HashString(uniqueID)
End Sub
Private Function GetUniqueID() As String
Dim result As String = GetOSSerialNumber()
Dim processorIDs() As String = GetProcessorIDs()
If ((processorIDs IsNot Nothing) AndAlso (processorIDs.Count > 0)) Then
result &= processorIDs(0)
End If
Return result
End Function
Private Function GetProcessorIDs() As String()
Dim result As New List(Of String)
Dim searcher = New System.Management.ManagementObjectSearcher("Select ProcessorId from Win32_Processor")
For Each managementObj In searcher.Get()
result.Add(CStr(managementObj.Properties("ProcessorId").Value))
Next
Return result.ToArray()
End Function
Private Function GetOSSerialNumber() As String
Dim result As String = ""
Dim searcher = New System.Management.ManagementObjectSearcher("Select SerialNumber from Win32_OperatingSystem")
For Each managementObj In searcher.Get()
result = CStr(managementObj.Properties("SerialNumber").Value)
Next
Return result
End Function
Public Function CompressString(ByVal source As String) As String
Dim result As String = ""
Dim encoding As New Text.ASCIIEncoding()
Dim bytes() As Byte = encoding.GetBytes(source)
Using ms As New IO.MemoryStream
Using gzsw As New System.IO.Compression.GZipStream(ms, IO.Compression.CompressionMode.Compress)
gzsw.Write(bytes, 0, bytes.Length)
gzsw.Close()
result = Convert.ToBase64String(ms.ToArray)
End Using
End Using
Return result
End Function
Public Function DecompressString(ByVal source As String) As String
Dim result As String = ""
Dim bytes() As Byte = Convert.FromBase64String(source)
Using ms As New IO.MemoryStream(bytes)
Using gzsw As New System.IO.Compression.GZipStream(ms, IO.Compression.CompressionMode.Decompress)
Dim data(CInt(ms.Length)) As Byte
gzsw.Read(data, 0, CInt(ms.Length))
Dim encoding As New Text.ASCIIEncoding()
result = encoding.GetString(data)
End Using
End Using
Return result
End Function
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
End Try
Return encrypted
End Function
Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim decrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(input)
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
End Try
Return decrypted
End Function
Private Function HashString(ByVal source As String) As String
Dim encoding As New Text.ASCIIEncoding()
Dim bytes() As Byte = encoding.GetBytes(source)
Dim workingHash() As Byte = New System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(bytes)
Dim result As String = ""
For Each b In workingHash
result = result & b.ToString("X2")
Next
Return result
End Function
End Module
I'm trying to make rijndael work in CBC mode. I'm not exactly sure how should I do it. I think problem in my current code is that the stream is initialized every time in the beginning of encryption, so no avalanche effect occurs (same data is encrypted twice and the output of those two encryption is the same which it should not be).
I tried to initialize the cryptostream only once but then my coded crashed because the canwrite property of cryptostream goes to false after the first write to the cryptostream.
Here is the code what I have now:
Sub Main()
Dim rij As New RijndaelManaged
Dim iv(15) As Byte
Dim key(15) As Byte
Dim secret() As Byte = {59, 60, 61}
Dim cs As ICryptoTransform
Dim cstream As CryptoStream
Dim out() As Byte
Dim NewRandom As New RNGCryptoServiceProvider()
NewRandom.GetBytes(iv)
NewRandom.GetBytes(key)
rij = New RijndaelManaged()
rij.KeySize = 128
rij.Padding = PaddingMode.PKCS7
rij.Mode = CipherMode.CBC
rij.IV = iv
rij.Key = key
cs = rij.CreateEncryptor()
Dim ms_in As New MemoryStream
cstream = New CryptoStream(ms_in, cs, CryptoStreamMode.Write)
Using cstream
cstream.Write(secret, 0, 3)
End Using
out = ms_in.ToArray
Console.WriteLine(ArrayToString(out, out.Length))
Erase out
ms_in = New MemoryStream
cstream = New CryptoStream(ms_in, cs, CryptoStreamMode.Write)
Using cstream
cstream.Write(secret, 0, 3)
End Using
out = ms_in.ToArray
Console.WriteLine(ArrayToString(out, out.Length))
End Sub
and the conversion function to convert an array to string
Public Function ArrayToString(ByVal bytes() As Byte, ByVal length As Integer) As String
If bytes.Length = 0 Then Return String.Empty
Dim sb As New System.Text.StringBuilder(length)
Dim k As Integer = length - 1
Dim i As Integer
For i = 0 To k
sb.Append(Chr(bytes(i)))
Next
Return sb.ToString()
End Function
This is what I need:
cs = rij.CreateEncryptor()
Dim ms_in As New MemoryStream
cstream = New CryptoStream(ms_in, cs, CryptoStreamMode.Write)
Using cstream
cstream.Write(secret, 0, 3) 'encrypt
End Using
out = ms_in.ToArray
Console.WriteLine(ArrayToString(out, out.Length)) 'see the encrypted message
Erase out
Using cstream
cstream.Write(secret, 0, 3) 'encrypt, this will crash here and this is the problem I'm trying to solve
End Using
out = ms_in.ToArray
Console.WriteLine(ArrayToString(out, out.Length)) 'see the encrypted message this should not be the same as the first one
Try this:
Public Sub Run()
Dim key() As Byte = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
Dim plaintext1 As Byte() = {59, 60, 61}
Dim plaintext2 As Byte() = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, _
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, _
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, _
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 _
}
Roundtrip(plaintext1, key)
System.Console.WriteLine()
Roundtrip(plaintext2, key)
End Sub
Public Sub Roundtrip(ByRef plaintext As Byte(), ByRef key As Byte())
Dim rij As New RijndaelManaged
Dim iv(15) As Byte
Dim encryptor As ICryptoTransform
Dim decryptor As ICryptoTransform
Dim out() As Byte
'Dim NewRandom As New RNGCryptoServiceProvider()
'NewRandom.GetBytes(iv)
'NewRandom.GetBytes(key)
Console.WriteLine("Original:")
Console.WriteLine(ArrayToString(plaintext))
System.Console.WriteLine()
rij = New RijndaelManaged()
rij.KeySize = key.Length * 8 ' 16 byte key == 128 bits
rij.Padding = PaddingMode.PKCS7
rij.Mode = CipherMode.CBC
rij.IV = iv
rij.Key = key
encryptor = rij.CreateEncryptor()
Using msIn = New MemoryStream
Using cstream = New CryptoStream(msIn, encryptor, CryptoStreamMode.Write)
cstream.Write(plaintext, 0, plaintext.Length)
End Using
out = msIn.ToArray
Console.WriteLine("Encrypted:")
Console.WriteLine("{0}", ArrayToString(out))
System.Console.WriteLine()
End Using
decryptor = rij.CreateDecryptor()
Using msIn = New MemoryStream
Using cstream = New CryptoStream(msIn, decryptor, CryptoStreamMode.Write)
cstream.Write(out, 0, out.Length)
End Using
out = msIn.ToArray
Console.WriteLine("Decrypted: ")
Console.WriteLine("{0}", ArrayToString(out))
System.Console.WriteLine()
End Using
End Sub
Public Shared Function ArrayToString(ByVal bytes As Byte()) As String
Dim sb As New System.Text.StringBuilder()
Dim i As Integer
For i = 0 To bytes.Length-1
if (i <> 0 AND i mod 16 = 0) Then
sb.Append(Environment.NewLine)
End If
sb.Append(System.String.Format("{0:X2} ", bytes(i)))
Next
Return sb.ToString().Trim()
End Function
I made these basic changes to get it to work:
create a Decryptor
properly manage buffers and streams (see the Using clauses I added)
I also re-organized a little, and modified your code slightly to use a constant IV (all zeros) and use a constant key. This is so that you can get repeatable results from one run to the next. In a real app you would use a randomized IV and use a password-derived key. (See Rfc2898DeriveBytes)
ok, that allows the code to compile. I think you want to see the effect of chaining. That is not so easy, but maybe something like this will show you what you want to see:
For i As Integer = 1 To 2
Using ms = New MemoryStream
Using cstream = New CryptoStream(ms, encryptor, CryptoStreamMode.Write)
For j As Integer = 1 To i
cstream.Write(plaintext, 0, plaintext.Length)
Next j
End Using
out = ms.ToArray
Console.WriteLine("Encrypted (cycle {0}):", i)
Console.WriteLine("{0}", ArrayToString(out))
System.Console.WriteLine()
End Using
Next i