Option Explicit
Sub test()
'this sub is only present to demonstrate use of the two functions!
'it is not required to use the functions.
Dim myString As String, holdingString As String, myKey As String
Application.ScreenUpdating = False
'sample string to encrypt:
myString = InputBox("Enter string to encrypt")
myKey = InputBox("Enter encryption key to use")
If Len(myString) = 0 Or Len(myKey) = 0 Then MsgBox "Invalid argument(s) used": Exit Sub
'report your entered string:
MsgBox "This is the string you entered: " & vbCr & myString
'run encryption function:
holdingString = XorEncrypt(myString, myKey)
'report encrypted string:
MsgBox "This is the encrypted string: " & vbCr & holdingString
'Decrypt encrypted string (by reversing process - must use exactly the same key
'(it is case-sensitive)
holdingString = XorDecrypt(holdingString, myKey)
'report decrypted string:
MsgBox "And decrypted: " & vbCr & holdingString
End Sub
Function XorEncrypt(ByVal sData As String, ByVal sKey As String) As String
Dim l As Long, i As Long, byIn() As Byte, SOut() As String, byKey() As Byte
If Len(sData) = 0 Or Len(sKey) = 0 Then XorEncrypt = "Invalid argument(s) used": Exit Function
byIn = StrConv(sData, vbFromUnicode)
ReDim SOut(LBound(byIn) To UBound(byIn))
byKey = StrConv(sKey, vbFromUnicode)
l = LBound(byKey)
For i = LBound(byIn) To UBound(byIn) Step 1
SOut(i) = byIn(i) Xor byKey(l)
l = l + 1
If l > UBound(byKey) Then l = LBound(byKey)
Next i
XorEncrypt = Join(SOut, ",")
End Function
Function XorDecrypt(ByVal sData As String, ByVal sKey As String) As String
Dim i As Long, l As Long, byOut() As Byte, sIn() As String, byKey() As Byte
If Len(sData) = 0 Or Len(sKey) = 0 Then XorDecrypt = "Invalid argument(s) used": Exit Function
sIn = Split(sData, ",")
ReDim byOut(LBound(sIn) To UBound(sIn))
byKey = StrConv(sKey, vbFromUnicode)
l = LBound(byKey)
For i = LBound(sIn) To UBound(sIn) Step 1
byOut(i) = Val(sIn(i)) Xor byKey(l)
l = l + 1
If l > UBound(byKey) Then l = LBound(byKey)
Next i
XorDecrypt = StrConv(byOut, vbUnicode)
End Function