Option Explicit On
Option Strict On
Imports System
Imports System.Text
Imports System.IO
Imports System.Security.Cryptography
Public Class myCrypto
Shared Sub New()
End Sub
Public Shared Function EncryptString(ByVal AString As String) As String
If AString = String.Empty Then
Return AString
Else
Dim encryptedData() As Byte
Dim dataStream As MemoryStream
Dim encryptor As ICryptoTransform
encryptor = mProvider.CreateEncryptor()
Try
dataStream = New MemoryStream
Dim encryptedStream As CryptoStream
Try
'Create the encrypted stream
encryptedStream = New CryptoStream(dataStream, encryptor,
CryptoStreamMode.Write)
Dim theWriter As StreamWriter
Try
'Write the string to memory via the encryption algorithm
theWriter = New StreamWriter(encryptedStream)
'Write the string to the memory stream
theWriter.Write(AString)
'End the writing
theWriter.Flush()
encryptedStream.FlushFinalBlock()
'Position back at start
dataStream.Position = 0
'Create area for data
ReDim encryptedData(CInt(dataStream.Length))
'Read data from memory
dataStream.Read(encryptedData, 0, CInt(dataStream.Length))
'Convert to String
Return Convert.ToBase64String(encryptedData, 0,
encryptedData.Length)
Finally
theWriter.Close()
End Try
Finally
encryptedStream.Close()
End Try
Finally
dataStream.Close()
End Try
End If
End Function
Public Shared Function DecryptString(ByVal AString As String) As String
If AString = String.Empty Then
Return AString
Else
Dim encryptedData() As Byte
Dim dataStream As MemoryStream
Dim encryptedStream As CryptoStream
Dim strLen As Integer
'Get the byte data
encryptedData = Convert.FromBase64String(AString)
Try
dataStream = New MemoryStream
Try
'Create decryptor and stream
Dim decryptor As ICryptoTransform
decryptor = mProvider.CreateDecryptor()
encryptedStream = New CryptoStream(dataStream, decryptor,
CryptoStreamMode.Write)
'Write the decrypted data to the memory stream
encryptedStream.Write(encryptedData, 0, encryptedData.Length -
1)
encryptedStream.FlushFinalBlock()
'Position back at start
dataStream.Position = 0
'Determine length of decrypted string
strLen = CInt(dataStream.Length)
'Create area for data
ReDim encryptedData(strLen - 1)
'Read decrypted data to byte()
dataStream.Read(encryptedData, 0, strLen)
'Construct string from byte()
Dim retStr As String
Dim i As Integer
For i = 0 To strLen - 1
retStr += Chr(encryptedData(i))
Next
'Return result
Return retStr
Finally
encryptedStream.Close()
End Try
Finally
dataStream.Close()
End Try
End If
End Function
End Class
--
Joe Fallon
"Robert Bull" <ro*********@wbp.org> wrote in message
news:bf**************************@posting.google.c om...
I am looking for an example of encryption/decryption in asp.net. I
want to encrypt a string before I send it to a Web Service, decrypt it
on the Web Service then encrypt the results on the Web Service and
decrypt the results on the web app. Any example using
System.Security.Cryptography namespace (VB not C#, thanks)would be
greatly appreciated. Thanks in advance.
-Rob