Untitled
unknown
python
a year ago
2.0 kB
2
Indexable
Never
#playfair cipher def playfair(plaintext, key): #remove spaces and make all letters lowercase plaintext = plaintext.replace(' ', '') plaintext = plaintext.lower() key = key.replace(' ', '') key = key.lower() #remove duplicate letters from key key = ''.join(sorted(set(key), key=key.index)) #remove j from key key = key.replace('j', '') #add key to matrix matrix = [] for c in key: matrix.append(c) #add remaining letters to matrix for c in 'abcdefghiklmnopqrstuvwxyz': if c not in key: matrix.append(c) #print matrix print('Matrix:') for i in range(0, 25, 5): print(matrix[i:i+5]) #add x between duplicate letters for i in range(0, len(plaintext)-1, 2): if plaintext[i] == plaintext[i+1]: plaintext = plaintext[:i+1] + 'x' + plaintext[i+1:] #add x to end if plaintext is odd length if len(plaintext) % 2 != 0: plaintext += 'x' #print plaintext print('Plaintext: %s' % plaintext) #encrypt plaintext ciphertext = '' for i in range(0, len(plaintext), 2): #find position of letters in matrix pos1 = matrix.index(plaintext[i]) pos2 = matrix.index(plaintext[i+1]) #find row and column of letters in matrix row1 = pos1 // 5 col1 = pos1 % 5 row2 = pos2 // 5 col2 = pos2 % 5 #encrypt letters if row1 == row2: ciphertext += matrix[row1*5 + (col1+1)%5] ciphertext += matrix[row2*5 + (col2+1)%5] elif col1 == col2: ciphertext += matrix[((row1+1)%5)*5 + col1] ciphertext += matrix[((row2+1)%5)*5 + col2] else: ciphertext += matrix[row1*5 + col2] ciphertext += matrix[row2*5 + col1] #print ciphertext print('Ciphertext:', ciphertext) return #main plaintext = 'Welcometomysecuritycourse' key = 'PLAYFAIR' playfair(plaintext, key)