Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Intermediate
May 4, 1999

Encrypt a String Easily

This quick and dirty encryption/decryption function takes whatever string you pass it, assigns it to a byte array, Xor's each byte by a constant, then returns the string. The offsetting done on every other character adds just a little to the confusion. Passing a string through the function once encrypts it; passing it through a second time decrypts it.

This function won't fool anyone from the National Security Agency, but it does protect the data from 99 percent of prying eyes, which is good enough for everything I ever need to do. It's only a few lines of code, but it encrypts as much data as you can fit into a string, and does so quickly:

 
	Private Sub Form_Click()
		Dim szTest As String

		szTest = "My dog has fleas."

		''' Passing the string through the function once 
		''' encrypts it.
		szTest = szEncryptDecrypt(szTest)
		Debug.Print szTest

		''' Passing the string through the function again 
		''' decrypts it.
		szTest = szEncryptDecrypt(szTest)
		Debug.Print szTest
	End Sub

Function szEncryptDecrypt(ByVal szData As String) As String
	''' This key value can be changed to alter the 
	''' encryption, but it must be the same for both 
	''' encryption and decryption.
	Const KEY_TEXT As String = "ScratchItYouFool"
	''' The KEY_OFFSET is optional, and may be any 
	''' value 0-64.
	''' Likewise, it needs to be the same coming/going.
	Const KEY_OFFSET As Long = 38

	Dim bytKey() As Byte
	Dim bytData() As Byte
	Dim lNum As Long
	Dim szKey As String

	For lNum = 1 To ((Len(szData) \ Len(KEY_TEXT)) + 1)
		szKey = szKey & KEY_TEXT
	Next lNum

	bytKey = Left$(szKey, Len(szData))
	bytData = szData

	For lNum = LBound(bytData) To UBound(bytData)
		If lNum Mod 2 Then
			bytData(lNum) = bytData(lNum) Xor (bytKey(lNum) _
				+ KEY_OFFSET)
		Else
			bytData(lNum) = bytData(lNum) Xor (bytKey(lNum) _
				- KEY_OFFSET)
		End If
	Next lNum

	szEncryptDecrypt = bytData
End Function
Rob Bovey
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap