Hi,
I am trying to write XOR encoding/decoding for B4X (I need to use it as a light weight and fast encoding/decoding cross plateforme solution with B4I, B4A, B4J and Lazarus/FPC). I know XOR is not the best/strongest encryption solution but it should be ok for my needs).
The following code works but need Base64 encoding first (I was not able to directly encode a string with XOR when the initial string has non-ascii chars ie UTF-8).
It would be great if someone knows a way to avoid the base64 encoding and help to increase the speed of this code
Thanks!
I am trying to write XOR encoding/decoding for B4X (I need to use it as a light weight and fast encoding/decoding cross plateforme solution with B4I, B4A, B4J and Lazarus/FPC). I know XOR is not the best/strongest encryption solution but it should be ok for my needs).
The following code works but need Base64 encoding first (I was not able to directly encode a string with XOR when the initial string has non-ascii chars ie UTF-8).
It would be great if someone knows a way to avoid the base64 encoding and help to increase the speed of this code
B4X:
Sub Button1_Click
Dim str As StringUtils
Dim aStr1 As String
Dim aStr2 As String
Dim b As ByteConverter
Dim By() As Byte
Dim DT As Long = DateTime.Now
For i = 0 To 1000000
aStr1 = str.EncodeBase64("ABCéè§ê:/%$€".GetBytes("UTF-8"))
aStr1 = XorEncode("MyKey", aStr1)
aStr2 = XorDecode("MyKey", aStr1)
By = str.DecodeBase64(aStr2)
aStr2 = B.StringFromBytes(By, "UTF-8")
Next
Log("Ellapsed Time: " & (DateTime.Now - DT))
End Sub
Sub XorEncode(Key As String, Source As String) As String
Dim b As ByteConverter
Dim IntVal As Int
Dim IntVal As Int
Dim aStrVal As String
Dim aResult As StringBuilder
aResult.Initialize
Dim S1() As Byte = b.StringToBytes(Source, "UTF-8")
Dim k1() As Byte = b.StringToBytes(Key, "UTF-8")
For i = 0 To S1.Length-1
IntVal = Bit.Xor(k1(i Mod k1.Length), S1(i))
aStrVal = Bit.ToHexString(IntVal)
If aStrVal.Length = 1 Then aStrVal = "0" & aStrVal
aResult.Append(aStrVal)
Next
Return aResult.ToString
End Sub
Sub XorDecode(Key As String, Source As String) As String
Dim b As ByteConverter
Dim aResult As String = ""
Dim S1() As Byte = b.HexToBytes(Source)
Dim k1() As Byte = b.StringToBytes(Key, "UTF-8")
Dim ByteVals(S1.Length) As Byte
For i = 0 To S1.Length -1
ByteVals(i) = Bit.Xor(k1(i Mod k1.Length), S1(i))
Next
aResult = BytesToString(ByteVals, 0, ByteVals.Length, "UTF-8")
Return aResult
End Sub
Thanks!