This example will show you how to use public and private keys to encrypt data.
First off lets create a class and call it CryptoService:
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Public Class CryptoService
Now we are going to add a two properties and two methods to our class. The properties will hold the public and private keys and the methods
will encrypt and decrypt the data we pass. Lets start with the properties first:
We will first add two private variables to our class to store the property data:
Private bytKey() As Byte
Private strKey As String
Now lets add our two properties:
Public Property Key() As Byte()
Get
Return bytKey
End Get
Set(ByVal KeyIn() As Byte)
If KeyIn.Length < 8 Or KeyIn.Length > 8 Then
Exit Property
End If
bytKey = KeyIn
End Set
End Property
Public Property KeyString() As String
Get
Return strKey
End Get
Set(ByVal KeyStringIn As Byte)
If KeyStringIn.Length < 8 Or KeyString.Length > 8 Then
Exit Property
End If
strKey = KeyStringIn
End Set
End Property
Notice that we will only except 8 numbers for our Key and 8 chars for our KeyString.
Now we will add the heart of the class with the two methods Encrypt and Decrypt:
Public Function Encrypt(ByVal Data As String) As String
If Data = "" Then
Exit Function
End If
If Key.Length = 0 Or KeyString = "" Then
Exit Function
End If
Dim bytKeys() As Byte = Encoding.UTF8.GetBytes(KeyString)
Dim bytIn() As Byte = Encoding.UTF8.GetBytes(Data)
Dim objMs As New MemoryStream
Dim objDes As New DESCryptoServiceProvider
Dim objCs As New CryptoStream(objMs, objDes.CreateEncryptor(bytKeys, Key), CryptoStreamMode.Write)
objCs.Write(bytIn, 0, bytIn.Length)
objCs.FlushFinalBlock()
Return Convert.ToBase64String(objMs.ToArray())
End Function
Public Function Decrypt(ByVal Data As String) As String
If Data = "" Then
Exit Function
End If
If Key.Length = 0 Or KeyString = "" Then
Exit Function
End If
Dim bytKeys() As Byte = Encoding.UTF8.GetBytes(KeyString)
Dim bytIn(Data.Length) As Byte
Dim objMs As New MemoryStream
Dim objDes As New DESCryptoServiceProvider
bytIn = Convert.FromBase64String(Data)
Dim objCs As New CryptoStream(objMs, objDes.CreateDecryptor(bytKeys, Key), CryptoStreamMode.Write)
objCs.Write(bytIn, 0, bytIn.Length)
objCs.FlushFinalBlock()
Return Encoding.UTF8.GetString(objMs.ToArray)
End Function
This class is now ready to be used to encrypt and decrypt data based upon the keys we submit to the class, for example:
Dim objCrypto As New CryptoService
objCrypto.Key = New Byte() {100, 20, 32, 77, 65, 89, 44, 2}
objCrypto.KeyString = "!#e^*h&="
Dim strEnc As String = objCrypto.Encrypt("my string")
Dim strDec As String = objCrypto.Decrypt(strEnc)
MessageBox.Show("Encrypted Data: " & strEnc & vbCrLf & "Decrypted Data: " & strDec)
I'll be posting more examples as I have time. If you would like me to make an example of something specific, just let me know.
Originally posted 6/8/2004 by pre
Posted
Jun 8, 2004 12:00 AM
by
ZoneServ