Encrypt a String Easily

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 SubFunction 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 = bytDataEnd Function
See also  5 Tips for Choosing the Right Medical Software for Your Practice

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist