Code:
Imports System.Security.Cryptography
Imports System.IO
Public Class CryptoMemoryStream
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
' Create a new DES key.
Using key As New DESCryptoServiceProvider()
' Encrypt a string to a byte array.
Dim buffer As Byte() = Encrypt(TextBox1.Text, key)
' Display the unicodesbytestostring value to the textboxes.
TextBox2.Text = UnicodeBytesToString(buffer)
TextBox3.Text = UnicodeBytesToString(buffer)
End Using
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Message")
End Try
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Try
Using key As New DESCryptoServiceProvider()
' Decrypt the byte array back to a string.
Dim buffer As Byte() = Encrypt(TextBox1.Text, key)
Dim plaintext As String = Decrypt(buffer, key)
' Display the plaintext value to the textbox4.
TextBox4.Text = plaintext
End Using
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Message")
End Try
End Sub
'Convert the bytes from a byte array into a string
Private Shared Function UnicodeBytesToString(ByVal bytes() As Byte) As String
Return System.Text.Encoding.Unicode.GetString(bytes)
End Function
' Encrypt the string.
Public Shared Function Encrypt(PlainText As String, key As SymmetricAlgorithm) As Byte()
' Create a memory stream.
Dim ms As New MemoryStream()
' Create a CryptoStream using the memory stream and the
' CSP DES key.
Dim encStream As New CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write)
' Create a StreamWriter to write a string
' to the stream.
Dim sw As New StreamWriter(encStream)
' Write the plaintext to the stream.
sw.WriteLine(PlainText)
' Close the StreamWriter and CryptoStream.
sw.Close()
encStream.Close()
' Get an array of bytes that represents
' the memory stream.
Dim buffer As Byte() = ms.ToArray()
' Close the memory stream.
ms.Close()
' Return the encrypted byte array.
Return buffer
End Function 'Encrypt
' Decrypt the byte array.
Public Shared Function Decrypt(CypherText() As Byte, key As SymmetricAlgorithm) As String
' Create a memory stream to the passed buffer.
Dim ms As New MemoryStream(CypherText)
' Create a CryptoStream using the memory stream and the
' CSP DES key.
Dim encStream As New CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read)
' Create a StreamReader for reading the stream.
Dim sr As New StreamReader(encStream)
' Read the stream as a string.
Dim val As String = sr.ReadLine()
' Close the streams.
sr.Close()
encStream.Close()
ms.Close()
Return val
End Function 'Decrypt
End Class