KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Encryption using XOR Bitwise
PRODUCT: 4D | VERSION: 13.3 | PLATFORM: Mac & Win
Published On: December 16, 2013

Here is a utility method to encrypt and decrypt a string using XOR bitwise (in Red). Please note that the input string needs to be the same length with the key.

// Method: encryptDecryptXORString
// Description:
// The method takes in a string to encrypt/decrypt and a string for the Key.
// Each character of the string to encrypt/decrypt will be XOR bitwise with each
// character of the Key. The method serves as a dual functionality for encrypting and
// decrypting a string with a given Key.
//
// Parameters:
// $1 (Text) - String for encrypt/decrypt
// $2 (Text) - Key to encrypt/decrypt
// $0 (Text) - Output string of encrypt/encrypt
// ----------------------------------------------------

C_TEXT($0;$outString)
C_TEXT($1;$inString;$2;$keyString)
C_TEXT($char1;$char2)
C_LONGINT($i)

$inString:=$1
$keyString:=$2

//Encrypting/decrypting the data using XOR
For ($i;1;Length($inString))
  $char1:=Substring($inString;$i;1)
  $char2:=Substring($keyString;$i;1)

 //XOR bitwise character by character
  $outString:=$outString+Char(Character code($char1) ^| Character code($char2))
End for

$0:=$outString



Below is an example of how the method encryptDecryptXORString can encrypt a string:

C_TEXT($data_str;$key_str;$encrypted_str;$decrypted_str)
$data_str:="4D_PASS" //String for encrypt/decrypt
$key_str:="78WxM0<" //Key to encrypt/decrypt

$encrypted_str:=encryptDecryptXORString($data_str;$key_str)


Result of the encrypted string: "|(\fco"
Note: The text displayed can be unreadable but it is accounted for in the text variable.


With the same method, an encrypted string can be decrypted:

$decrypted_str:=encryptDecryptXORString($encrypted_str;$key_str)


Result of the decrypted string returns the original input string: "4D_PASS"