W
W
WhiteNiBBa2020-10-29 22:33:39
Python
WhiteNiBBa, 2020-10-29 22:33:39

How to write Playfair cipher in python?

At the laboratory, they were asked to write an encoder and decoder of the Playfair cipher. To begin with, I decided to write an encoder for a constant matrix. But something went wrong. To understand the work, I will explain how the cipher works. The input is a phrase. Then the following actions are performed:
1) If the word has 2 identical letters standing side by side, then a letter is inserted between them. (in this case, "I")
2) If the number of characters in the phrase is odd, then "I" is put at the end
3) The phrase is divided into conditional bigrams
4) A conditional square is built in the matrix, 2 opposite corners of which are letters from digrams.
5) Further, these letters are replaced by others located at the corners of the square (top or bottom)
6) If the letters are on the same line, then they are shifted to the right by 1.
7) If the letters are in the same column, then change by 1 down.
8) The phrase is going back
Here is my code, which encrypts some characters normally, and some does not

text = input('Введите текст : ')
text = [x for x in text]
res = ''
m = [
    ["Н","И","К","О","Л","А"],
    ["Б","В","Г","Д","Е","Ё"],
    ["Ж","З","Й","М","П","Р"],
    ["С","Т","У","Ф","Х","Ц"],
    ["Ч","Ш","Щ","Ь","Ы","Ъ"],
    ["Э","Ю","Я",".","-","_"],
    ]
for i in range(1,len(text)):
    if text[i] == text[i-1]:
        text.insert(i,'Я')
if len(text)%2 != 0:
    text.append('Я')
for i in range(0,len(text),2):
    a1 = -1; a2 = -1; b1 = -1; b2 = -1
    for a in range(5):
        for b in range(5):
            if a1 == -1:
                if text[i] == m[a][b]:
                    a1 = a; b1 = b
            if a2 == -1:
                if text[i+1] == m[a][b]:
                    a2 = a; b2 = b
    if a1 == a2:
        if b1 == 5 or b2 == 5:
            if b1 == 5:
                b1 = 0
                b2 += 1
            else:
                b2 = 0
                b1 += 1
        
        else :
            b1 += 1
            b2 += 1
    else:
        if b1 == b2:
            if a1 == 5 or a2 == 5:
                if a1 == 5:
                    a1 = 0
                    a2 += 1
                else:
                    a2 = 0
                    a1 += 1
            
            else:
                a1 += 1
                a2 += 1
        else:
            a1,a2 = a2,a1
    res += m[a1][b1]
    res += m[a2][b2]
print(res)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmustache Usakov, 2021-02-04
@Dmustache

We were asked to hand it in today at 22, so I will not rewrite my code, here it is:

abc = ['а','б','в','г','д','е','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я']
specs = ' ,.:;-!?)('


sentense = [i.lower() for i in 'Пронеслась гроза седая']

for i in specs:
    while sentense.count(i) > 0:
        sentense.pop(sentense.index(i))
sentense = ''.join(sentense)

key = 'компас'
addSymbol = 'х'
preList = ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','']

for i in range(len(key)):
    preList[i] = key[i]

abcWithoutKey = abc
for i in key:
    abcWithoutKey.pop(abcWithoutKey.index(i))
abc = ['а','б','в','г','д','е','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я']

for i in range(len(key), len(preList)):
    preList[i] = abcWithoutKey[i - len(key)]

codeList = [
    ['','','','','','','',''],
    ['','','','','','','',''],
    ['','','','','','','',''],
    ['','','','','','','','']
]
tmp = 0
for i in range(4):
    for j in range(8):
        codeList[i][j] = preList[tmp]
        tmp += 1

del tmp, abcWithoutKey, specs, preList

sentenseReacharge = []
for i in range(0, len(sentense), 2):
    try:
        if sentense[i] != sentense[i + 1]:
            sentenseReacharge.append(sentense[i] + sentense[i + 1])
        else:
            sentense = sentense[:i + 1] + addSymbol + sentense[i + 1:]
            sentenseReacharge.append(sentense[i] + sentense[i + 1])
    except IndexError:
        sentenseReacharge.append(sentense[-1] + addSymbol)

del sentense

#for i in range(len(codeList)):
    #print(*codeList[i])

def takeIndex(code):
    global codeList
    ans = 
    return ans
    # 1 - столбец
    # 0 - строка

def Check(indexF, indexS):
    global codeList
    if indexF[0][1] == indexS[0][1]: #collumn
        (indexF[0][0] + 3) % 4, (indexS[0][0] + 3) % 4
    elif indexF[0][0] == indexS[0][0]: #line
        (indexF[0][1] + 7) % 8, (indexS[0][1] + 7) % 8
    else: #square
        buf = indexF[0][1]
        indexF[0][1] = indexS[0][1]
        indexS[0][1] = buf
    return indexF, indexS

codes = []
for code in sentenseReacharge:
    codes.append(Check(takeIndex(code[0]), takeIndex(code[1])))

#print(sentenseReacharge)
#print('строка, столбец')
AnswerIndex = ''
#print(codes)
for i in codes:
    #print(i[0][0][0], i[0][0][1], i[1][0][0], i[1][0][1])
    AnswerIndex += codeList[i[0][0][0]][i[0][0][1]]
    AnswerIndex += codeList[i[1][0][0]][i[1][0][1]]
print(AnswerIndex)

the problem is that it can't decode the 4 characters at the end. Why? don't know((
(The main magic happens in the last 10 lines) Here's where it does
n't decipher:
The thunderstorm
flashed by

G
ghostgimli, 2021-03-25
@ghostgimli

I myself wondered while I was looking, edited your code and it turned out to be working
Ps It's a bit late, but maybe for future generations it will be in the subject

text = input('Введите текст : ')
text = [x for x in text]
res = ''
m = [
    ["Н","И","К","О","Л","А"],
    ["Б","В","Г","Д","Е","Ё"],
    ["Ж","З","Й","М","П","Р"],
    ["С","Т","У","Ф","Х","Ц"],
    ["Ч","Ш","Щ","Ь","Ы","Ъ"],
    ["Э","Ю","Я",".","-","_"],
    ]
for i in range(1,len(text)):
    if text[i] == text[i-1]:
        text.insert(i,'Я')
if len(text)%2 != 0:
    text.append('Я')
print(text)
for k in range(0,len(text),2):# Берём по два аргумента
    x1=-1;x2=-1;y1=-1;y2=-1
    for i in range(6):
       for j in range(6):
           if x1 == -1:
              if text[k] == m[i][j]:
                  x1=i;    y1=j
           if x2 == -1:
               if text[k+1] == m[i][j]:
                   x2=i;    y2=j
    if x1== x2:
        if y1==5:
            y1=0
            y2+=1
        elif y2 == 5:
            y1+=1
            y2=0
        else:
            y1+=1
            y2+=1
    elif y1 == y2:
        if  x1 ==5 and x2 ==5:
            x1 = 0;     x2= 0
        elif x1 == 5:
            x1=0;   x2+=1
        elif x2 == 5:
            x2=0;   x1+=1
        else:
            x2+=1;  x1+=1
    else:
        temp=0
        temp=y1
        y1=y2
        y2=temp
    text[k]=m[x1][y1]
    text[k+1]=m[x2][y2]
print(text)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question