Advertisement
asteroidsteam

Cypher

May 6th, 2019
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1.  
  2.  
  3.  
  4. #FILE USAGE:
  5. #python3 <thisfile.py> <key> <message> [-d for decoding (optional)]
  6.  
  7.  
  8.  
  9. import sys;
  10.  
  11. strs = 'abcdefghijklmnopqrstuvwxyz1234567890 '      #use a string like this, instead of ord()
  12. def shifttext(shift,inp):
  13.     data = []
  14.     for i in inp:                     #iterate over the text not some list
  15.         if i.strip() and i in strs:                 # if the char is not a space ""  
  16.             data.append(strs[(strs.index(i) + shift) % len(strs)])    
  17.         else:
  18.             data.append(i)           #if space the simply append it to data
  19.     output = ''.join(data)
  20.     return output
  21.  
  22. def gentable():
  23.     table = [];
  24.     for i in range(0,len(strs)+1):
  25.         table.append(shifttext(i,strs));
  26.     return table;
  27. def getIndex(letter):
  28.     x = 0;
  29.     for i in strs:
  30.         if letter == i:
  31.             return x;
  32.         x += 1;
  33.     return 39;
  34. table = gentable();
  35. def getAlphabet(index):
  36.     return table[index];
  37. def getLetterD(index,letter):
  38.     for alph in table:
  39.         if alph[index] == letter:
  40.             return alph[0];
  41. def getLetter(index,alphabet):
  42.     return alphabet[index];
  43. def encode(toEncode_,codeword_):
  44.     i=0;
  45.     word = '';
  46.     for c in toEncode_:
  47.         v = codeword_[i];
  48.         word += getLetter(getIndex(v),getAlphabet(getIndex(c)));
  49.         i+=1;
  50.         if i >= len(codeword_):
  51.             i = 0;
  52.     return(word);
  53. def decode(toDecode_,codeword_):
  54.     i=0;
  55.     word = '';
  56.     for c in toDecode_:
  57.         v = codeword_[i];
  58.         word+=getLetterD(getIndex(v),c);
  59.         i+=1;
  60.         if i >= len(codeword_):
  61.             i = 0;
  62.     return(word);
  63. codeword = ''
  64. esd = ''
  65. decodeM = False
  66. if len(sys.argv) >= 2:
  67.     codeword = sys.argv[1];
  68.     esd = ''
  69.     decodeM = False;
  70.     for i in range(2,len(sys.argv)):
  71.         if sys.argv[i] == '-d':
  72.             decodeM = True
  73.         else:
  74.             esd += sys.argv[i] + " ";
  75.     if (esd == ''):
  76.         print("Usage: python3 {0} code input [-d (DECODE MODE)]".format(sys.argv[0]));
  77.         sys.exit();
  78. else:
  79.     print("Usage: python3 {0} code input [-d (DECODE MODE)]".format(sys.argv[0]));
  80.     sys.exit();
  81. esd = esd[:-1]
  82. if (decodeM):
  83.     print('"'+decode(esd,codeword)+'"');
  84. else:
  85.     print('"'+encode(esd,codeword)+'"');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement