Skip to content

Instantly share code, notes, and snippets.

@isaidnocookies
Created June 27, 2020 02:37
Show Gist options
  • Save isaidnocookies/b4c4632495d297e11ac0be0bd2ccf589 to your computer and use it in GitHub Desktop.
Save isaidnocookies/b4c4632495d297e11ac0be0bd2ccf589 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import argparse
import math
def CantorPairing(x,y):
"""
Turns the x,y pair into a Cantor Pairing value
Args:
x (int): x coordinate value
y (int): y coordinate value
returns:
int: Cantor Pairing value
"""
z = ((x + y) * (x + y + 1)) / 2 + y
return int(z)
def CantorDepairing(z):
"""
Depairs the Cantor value back into an x,y coordinate
Args:
z (int): Cantor Pairing value
Returns:
dict: Dictionary containing "x" and "y" keys. each value associated with the keys is an int
"""
t = math.floor((-1 + math.sqrt(1 + 8 * z))/2)
x = t * (t + 3) / 2 - z
y = z - t * (t + 1) / 2
pair = {"x": x, "y":y}
return pair
def CantorCipherEncrypt(v):
"""
Encrypts the value v with the Cantor Cipher (Cipher that takes character pairs and converts them into a single Cantor Pairing value)
If the plaintext includes an odd number of characters, an "x" is appended to the end in order to properly split the string
into "x,y" pairs.
Args:
v (str): Plaintext to be encrypted
Returns:
str: String of comma-seperated values represented the encoded plaintext
"""
plaintext = v
if (len(plaintext) % 2 != 0):
plaintext += "x"
cantorValues = []
for i in range (0, len(plaintext), 2):
x = ord(plaintext[i])
y = ord(plaintext[i+1])
cantorValue = CantorPairing(x,y)
cantorValues.append(str(cantorValue))
return ",".join(cantorValues)
def CantorCipherDecrypt(v):
"""
Decrypts the string v from the Cantor Cipher. V should be a comma-sperated list of Cantor values.
Args:
v (str): String of comma seperated integers
Returns:
str: Plaintext associated with the ciphertext v
"""
cipherText = v.replace(" ", "")
cipherArray = cipherText.split(',')
characters = []
for value in cipherArray:
coords = CantorDepairing(int(value))
characters.append(chr(int(coords["x"])))
characters.append(chr(int(coords["y"])))
return "".join(characters)
def main():
parser = argparse.ArgumentParser(description='Cantor Cipher Tool.')
parser.add_argument('-i', '--input', action='store', type=str, help='Value to be converted')
parser.add_argument('--decrypt', '-d', help='Print more data', action='store_true')
args = parser.parse_args()
if (args.input == "" or args.input == None):
parser.print_help()
quit()
if(args.decrypt):
try:
print(CantorCipherDecrypt(args.input))
except:
print("Failed to decrypt input. Format must be comma seperated integers representing the Cantor Pairing values. Please check format and try again.")
else:
print(CantorCipherEncrypt(args.input))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment