-
-
Save nawie/028c85e29503a5e2d8de106ebd972017 to your computer and use it in GitHub Desktop.
Simple python XOR encrypt/decrypt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# NB : this is not secure | |
# from http://code.activestate.com/recipes/266586-simple-xor-keyword-encryption/ | |
# added base64 encoding for simple querystring :) | |
# | |
# modify for compatibility on python 3 | |
import sys | |
import base64 | |
from itertools import cycle | |
if sys.version_info[0] < 3: # if python 2 | |
from itertools import izip | |
def _encode_string(string): | |
return base64.encodestring(string) | |
def _decode_string(string): | |
return base64.decodestring(string) | |
else: | |
izip = zip | |
def _encode_string(string): | |
return base64.encodebytes(string.encode()).decode() | |
def _decode_string(string): | |
return base64.decodebytes(string.encode()).decode() | |
key = 'h4shK3ys' | |
def _xored(value, key): | |
return chr(ord(value) ^ ord(key)) | |
def xor(data, keys): | |
data_pair = izip(data, cycle(keys)) | |
return ''.join(_xored(val, key) for (val, key) in data_pair) | |
def decode(data, keys=key): | |
data_decoded = _decode_string(data) | |
return xor(data_decoded, keys) | |
def encode(data, keys=key): | |
data_xored = xor(data, keys) | |
return _encode_string(data_xored).replace('\n', '') | |
if __name__ == "__main__": | |
keys = 's3cre7-h45h' | |
text = 'this is secret text 1@#@#/host:port' | |
enc = encode(text, keys) | |
dec = decode(enc, keys) | |
print('text:{}\nenc:"{}"\ndec:{}'.format(text, enc, dec)) | |
# Python 3.7.4 (default, Jul 9 2019, 00:06:43) | |
# [GCC 6.3.0 20170516] on linux | |
# text:this is secret text 1@#@#/host:port | |
# enc:"B1sKAUVeXkhHUAsBVhdSEVJVHBQEKFBzQF0NWF4cDkUHAUc=" | |
# dec:this is secret text 1@#@#/host:port | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment