Shorten a string containing data - vb.net

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

Related

VB NET AES encrypt

Can't reproduce an AES online encoder example using VB.Net
Trying in https://www.devglan.com/online-tools/aes-encryption-decryption with following parameters:
Text to be Encrypted: test
Cipher Mode: ECB
Key Size: 128
Secret Key: 1234567890123456
I get this output: 3fvaLg5IDlveswuXzhVQcw==
If I try in VB.Net using this function (found in https://gist.github.com/ShaneGowland/5973974):
Public Shared 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 = 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))
Return encrypted
Catch ex As Exception
Return ex.ToString
End Try
End Function
I get this output: 6mhZOr1dQ7PWqbRGzmMgjg== which is not matching with got at devglan.com
I tried with different paddings with no luck. What am I doing wrong?
PS: I am aware that the ECB method should not be used
Working with this function:
Public Shared 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
AES.Mode = CipherMode.ECB
AES.Key = Encoding.UTF8.GetBytes(pass)
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))
Return encrypted
Catch ex As Exception
Return ex.ToString
End Try
End Function

Chrome Native Messaging Host VB.Net

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

Problems with encryption and decryption TripleDES in vb.net

I'm practicing encryption and decryption with a text file by using TipleDES. I enter a word in a text box, which is in my application, and then click my button that will store the password in the text file. I check the text file to see if it encrypts it which it does and then I try to decrypt the text. It encrypts it again and doesn't decrypt it. I'm not sure what I'm doing wrong.
Public Function EncryptTripleDES(strInput As String, btKey As String) As String
Dim desTDES As New TripleDESCryptoServiceProvider()
Dim hashMD5TDES As New MD5CryptoServiceProvider()
Dim btHash As Byte()
Dim btBuff As Byte()
btHash = hashMD5TDES.ComputeHash(Encoding.UTF8.GetBytes(btKey))
desTDES.Key = btHash
desTDES.Mode = CipherMode.ECB
btBuff = Encoding.UTF8.GetBytes(strInput)
Dim strResult As String = Convert.ToBase64String _
(desTDES.CreateEncryptor().TransformFinalBlock(btBuff, 0,
btBuff.Length))
Return strResult
End Function
Public Function DecryptTripleDES(strInput As String, btKey As String) As String
Dim desTDES As New TripleDESCryptoServiceProvider()
Dim hashMD5TDES As New MD5CryptoServiceProvider()
Dim btHash As Byte()
Dim btBuff As Byte()
btHash = hashMD5TDES.ComputeHash(Encoding.UTF8.GetBytes(btKey))
desTDES.Key = btHash
desTDES.Mode = CipherMode.ECB
btBuff = Convert.FromBase64String(strInput)
Dim strResult As String = Encoding.UTF8.GetString _
(desTDES.CreateDecryptor().TransformFinalBlock(btBuff, 0,
btBuff.Length))
Return strResult
End Function
These are my functions to encrypt and decrypt.
strEncode = EncryptTripleDES(EmailPasswordTextBox.Text, "HTG")
strDecode = DecryptTripleDES(strEncode, "HTG")
Console.WriteLine("Encrypted: {0}", strEncode)
Console.WriteLine("Decrypted: {0}", strDecode)
If I change EmailPasswordTextBox.Text to "This is a Test". It works perfectly. What am I doing wrong?

VB.Net Encryption Function Not Decrypting Without Using Base64Encode

I am having a issue with decrypting, my goal is to be able to encrypt/decrypt with/without base64 encoding on the encrypted string. As of now I can encrypt/decrypt with base64 and encrypt without it but not decrypt without it. I get errors regarding the padding being incorrect.
Thanks in advance!
Here is my encryption/decryption function:
Public Function DoCryptWork(Type As String, Data As String) As String
Dim Pass As String = Hasher.TextBoxPassword.Text
Dim Salt As String = Hasher.TextBoxSalt.Text
Dim Vect As String = Hasher.TextBoxIntVector.Text
Select Case Type
Case "e"
Try
Dim PassPhrase As String = Pass
Dim SaltValue As String = Salt
Dim HashAlgorithm As String = My.Settings.HashAlgorithm
Dim PasswordIterations As Integer = 2
Dim InitVector As String = Vect
Dim KeySize As Integer = 256
Dim InitVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(SaltValue)
Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(Data)
Dim Password As New PasswordDeriveBytes(PassPhrase, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = Password.GetBytes(KeySize \ 8)
Dim SymmetricKey As New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitVectorBytes)
Dim MemoryStream As New MemoryStream()
Dim CryptoStream As New CryptoStream(MemoryStream, Encryptor, CryptoStreamMode.Write)
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
CryptoStream.FlushFinalBlock()
Dim CipherTextBytes As Byte() = MemoryStream.ToArray()
MemoryStream.Close()
CryptoStream.Close()
Dim CipherText As String = Nothing
If My.Settings.Base64EncodeMD5Hash = True Then
CipherText = Convert.ToBase64String(CipherTextBytes)
Return CipherText
Else
Dim TextCipher As New StringBuilder()
For n As Integer = 0 To CipherTextBytes.Length - 1
TextCipher.Append(CipherTextBytes(n).ToString("X2"))
Next n
CipherText = TextCipher.ToString()
Return CipherText
End If
Catch ex As Exception
MsgBox("Encryption was unsuccessfull!", MsgBoxStyle.Critical, "Error")
Return "Encryption was unsuccessfull!"
End Try
Case "d"
Try
Dim PassPhrase As String = Pass
Dim SaltValue As String = Salt
Dim HashAlgorithm As String = My.Settings.HashAlgorithm
Dim PasswordIterations As Integer = 2
Dim InitVector As String = Vect
Dim KeySize As Integer = 256
Dim InitVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(SaltValue)
Dim CipherTextBytes As Byte() = Nothing
If My.Settings.Base64EncodeMD5Hash = True Then
CipherTextBytes = Convert.FromBase64String(Data)
Else
Dim bytedata As Byte() = Encoding.UTF8.GetBytes(Data)
CipherTextBytes = bytedata
End If
Dim Password As New PasswordDeriveBytes(PassPhrase, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = Password.GetBytes(KeySize \ 8)
Dim SymmetricKey As New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitVectorBytes)
Dim MemoryStream As New MemoryStream(CipherTextBytes)
Dim CryptoStream As New CryptoStream(MemoryStream, Decryptor, CryptoStreamMode.Read)
Dim PlainTextBytes As Byte() = New Byte(CipherTextBytes.Length - 1) {}
Dim DecryptedByteCount As Integer = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length)
MemoryStream.Close()
CryptoStream.Close()
Dim PlainText As String = Encoding.UTF8.GetString(PlainTextBytes, 0, DecryptedByteCount)
Return PlainText
Catch Ex As Exception
MsgBox("Decryption was unsuccessfull!" & vbNewLine & vbNewLine & Ex.ToString(), MsgBoxStyle.Critical, "Error")
Return "Decryption was unsuccessfull!"
End Try
Case Else
Return "Error! Invalid Case Selected We should never see this but just to be safe we'll show this message if the wrong case is selected!"
End Select
Return True
End Function
I call the function as so:
TextBoxOutput.Text = Encryption.DoCryptWork("e", TextBoxInput.Text) ' encrypt data.
TextBoxOutput.Text = Encryption.DoCryptWork("d", TextBoxInput.Text) ' decrypt data.
When you convert the bytes to hex, you output two hex digits per byte. When you convert that hex back to bytes, you're converting every hex digit to a byte instead of every pair of hex digits.
Actually, I just took another look and noticed that you're not even keeping the earlier bytes. This loop:
For n As Integer = 0 To Data.Length - 1
CipherTextBytes = Convert.ToByte(Data(n))
Next n
sets CipherTextBytes on each iteration so you're going to replace the previous byte each time, so you only end up keeping the byte from the last digit.

How to make Rijndael CBC mode work in vb.net

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