python 密码加密_使用python3播放公平的密码加密

python 密码加密

Hi everyone since I’m into cryptography these days I thought why don’t I give a try to code the algorithms that are used to encrypt. My most favorite one is PlayFair Cipher, so I thought it would be easy to code but really took me a lot of hours. First let’s see what is PlayFair Cipher and working of the algorithm and then we can dive into the code.

大家好,自从我最近开始使用加密技术以来,我想为什么不尝试对用于加密的算法进行编码。 我最喜欢的一个是PlayFair Cipher,所以我认为编写代码会很容易,但确实花了我很多时间。 首先让我们看看什么是PlayFair密码以及算法的工作原理,然后我们可以深入研究代码。

PlayFair CipherIt is first practical digraph substitution cipher. It has 25*25 = 625 possible diagraphs. Diagraph means encrypt using 2 letter rather than 1 letter. Playfair is significantly harder to break since the frequency analysis used for simple substitution ciphers does not work with it.

PlayFair Cipher它是第一个实用的有向图替换密码。 它具有25 * 25 = 625个可能的图。 图表示使用2个字母而不是1个字母进行加密。 Playfair很难破解,因为用于简单替换密码的频率分析无法使用。

How does PlayFair Cipher Encryption algorithm work?

PlayFair密码加密算法如何工作?

I will explain with an example, so let us take plaintext as PASSIVE ATTACK IS STILL BAD and key is PROGRAMMING

我将通过一个示例进行说明,因此让我们采用纯文本格式,因为PASSIVE ATTACK仍然很糟糕,而key是PROGRAMMING

There are three steps in the algorithm:1. Separate the Plaintext into pairs of text.2. Generate Key Matrix or Key Square.3. Encrypt Plaintext using Key square or Key Matrix from step 2.STEP 1 : Separate the Plaintext into pair of text:Our plaintext is Passive attack is still bad, I am going to split the sentence into pairs of letter.

该算法分为三个步骤:1。 将纯文本分成成对的文本2。 生成密钥矩阵或密钥平方3。 从步骤2开始使用Key Square或Key Matrix加密纯文本。步骤1:将纯文本分为成对的文本:我们的纯文本是Passive Attack仍然很糟糕,我将句子分成字母对。

Here we go,[[p,a],[s,x],[s,i],[v,e],[a,t],[t,a],[c,k],[i,s],[s,t],[i,l],[l,b],[a,d]]

这里我们去[[p,a],[s,x],[s,i],[v,e],[a,t],[t,a],[c,k],[i, s],[s,t],[i,l],[l,b],[a,d]]

This is our plainText 2D List .

这是我们的plainText 2D列表。

Rules to be followed while splitting the plaintext are as follows, please read it carefully because this is the most important thing.

分割纯文本时要遵循的规则如下,请仔细阅读,因为这是最重要的。

1.While splitting text into pairs, if the letters are same in a pair then insert filler x .Filler, it can be low frequency alphabet i.e which occur less number of times in English words for example j, z, w etc.

1.将文本分成几对时,如果成对的字母相同,然后插入填充符x .Filler,它可以是低频字母,即英语单词中出现的次数较少,例如j,z,w等。

eg . for above plaintext I got a pair [s,s] ->[s,x]. If the letter are same we cannot encrypt it will be the same letter as before so we are inserting filler x before ‘s’.

例如。 对于上面的明文,我得到了一对[s,s]-> [s,x]。 如果字母相同,我们将无法对其进行加密,因此它将与之前的字母相同,因此我们在's'之前插入填充符x。

2. At the end if only one letter is left it has no pair we can insert our filler x.eg : consider red as plain text we can split it as [[r,e],[d,x]]

2.最后,如果只剩一个字母没有对,我们可以插入填充符x。例如:将红色视为纯文本,我们可以将其拆分为[[r,e],[d,x]]

3.If you want to keep spaces while encrypting you can replace white space with filler x.

3.如果要在加密时保留空格,可以用填充符x替换空白。

Let us dive into Step 2

让我们深入到步骤2

步骤2:产生金钥矩阵或金钥平方 (STEP 2 : Generate Key Matrix or Key Square)

Generating Key Matrix or Key Square of size 5*5, it will always be 5*5 because only 26 alphabets are there. Our Key is PROGRAMMINGThe Key Sqaure is

生成大小为5 * 5的键矩阵或键平方,由于那里只有26个字母,因此它将始终为5 * 5。 我们的关键是编程关键是

Image for post
fig 1:KEY MATRIX/KEY SQUARE
无花果1:关键矩阵/关键平方

Rules used to fill the key matrix/ key square are pretty simple. Here they are

用于填充密钥矩阵/密钥平方的规则非常简单。 他们来了

1.In our key there may be repeated letters while filling the key matrix/key square a letter should occur only one time so reduce our key where every letter occurs only once. In above example PROGRAMMING key is reduced to PROGAMIN

1.在我们的密钥中,当填充密钥矩阵/密钥方块时,可能会出现重复的字母,一个字母应该只出现一次,因此减少我们的密钥,因为每个字母只会出现一次。 在上面的示例中,PROGRAMMING键被简化为PROGAMIN

2.Rest of the boxes in the key matrix/ key square is filled by the rest of alphabets that are not present in key in lexicographical order.Then the important point i and j are considered as same in this matrix according to your problem statement fill I or J in the matrix . If both are present then represent both i and j as I or J. Since the Key I used here has ‘I’ in it I placed ‘I’ instead of ‘J’.

2,密钥矩阵/密钥方块中的其余方框由按字典顺序在密钥中不存在的其余字母填充,然后根据问题陈述的填充,将重要点i和j视为此矩阵中的相同点矩阵中的I或J。 如果两者都存在,则将i和j都表示为I或J。由于在此使用的密钥中包含“ I”,因此我放置了“ I”而不是“ J”。

3. If you feel little bit confused look at above image(fig 1) for reference.Now our key matrix is ready and we are going to encrypt our message(plaintext). And this is going to be real fun .

3.如果您感到有些困惑,请查看上面的图像(图1)以供参考。现在我们的密钥矩阵已准备就绪,我们将对消息进行加密(明文)。 这将是真正的乐趣。

步骤3:使用密钥平方/密钥矩阵对纯文本进行加密 (STEP 3 : Encrypt Plaintext using Key square /Key Matrix)

Our plaintext 2D List is [[p,a],[s,x],[s,i],[v,e],[a,t],[t,a],[c,k],[i,s],[s,t],[i,l],[l,b],[a,d]].

我们的明文2D列表为[[p,a],[s,x],[s,i],[v,e],[a,t],[t,a],[c,k],[i ,s],[s,t],[i,l],[l,b],[a,d]]。

Image for post

First we are going to encrypt ‘p’ and ‘a’. Look at the image above. Position of ‘p’ and ‘a’ are in same row but different column so encrypt the letter with letter in same row with next column.p->r , a->p

首先,我们将加密“ p”和“ a”。 看上面的图片。 'p'和'a'的位置在同一行中但在不同的列中,因此请使用与下一列在同一行中的字母对字母进行加密。 p-> r,a-> p

Image for post

Next is ‘s’ and ‘x’. Position of ‘s’ and ‘x’ are in different row but same column so encrypt the letter with letter in different row with same column. So ‘s’ is going to be ‘x’ and ‘x’ is ‘o’.s->x , x->o

接下来是“ s”和“ x”。 “ s”和“ x”的位置在不同的行中但在同一列中,因此请在同一列的不同行中用字母对字母进行加密。 因此,“ s”将是“ x”,“ x”是“ o”。 s-> x,x-> o

Image for post

Next is ‘s’ and ‘i’. Position of ‘s’ and ‘i’ are in different row but different column so encrypt the letter with letter present at intersection of ‘s’ and ‘i’ . So ‘s’ is going to be ‘q’ and ‘i’ is ‘n’.Here we keep our row constant and we are going to interchange the column only.so s->q , i->nSo do the same for every pair of letter present in the message.

接下来是“ s”和“ i”。 's'和'i'的位置在不同的行但在不同的列中,因此请使用在's'和'i'的交集处出现的字母来加密字母。 所以's'将是'q'并且'i'是'n'。在这里我们保持行不变,我们将只交换列。s- > q,i-> n消息中出现的每对字母。

Now I am going to summarize the rules that are used to encrypt the message for better understanding.

现在,我将总结用于加密消息的规则,以便更好地理解。

1.If the row of the letter in a pair is same then encrypt with letter at position same row but column+1 i.e next column

1.如果成对的字母行相同,则在同一行但列+1(即下一列)的位置用字母加密

2.If the column of the letter in a pair is same then encrypt with letter at position same column but row+1 i.e next row

2.如果一对字母的列相同,则在同一列但行+1(即下一行)的位置用字母加密

3.If the column and row both are different keep the row constant interchange the column that is for ‘s’ and ‘i’ . Position of ‘s’ is[3,2] (Note I started indexing from 0) and ‘i’ is [1,1] .So ‘s’ is encrypted with letter at position [3,1](row is same but column is interchanged) and that is ‘q’ and for ‘i’ is encrypted with letter at position [1,2] and that is ‘n’.

3.如果列和行都不同,则保持行常量互换用于s和i的列。 's'的位置是[3,2](请注意,我从0开始索引),'i'是[1,1]。因此,'s'在位置[3,1]用字母加密(行是相同的,但列互换),即为“ q”,对于“ i”,在位置[1,2]处用字母加密,即为“ n”。

Finally the encrypted message would look like RPXOQNWDGUUGKUQNTUMQTMPK

最后,加密后的消息看起来像RPXOQNWDGUUGKUQNTUMQTMPK

Hurray ! that’s it , Now you have learned the algorithm to encrypt the message using Playfair Cipher.

万岁! 就是这样,现在您已经了解了使用Playfair Cipher加密消息的算法。

Now we will dive into how to code the above algorithm using Python3. I will explain how to code the algorithm in 3 steps as I did for the algorithm. The three steps are as follows.1. Separate the Plaintext into pairs of text.2. Generate Key Matrix or Key Square3. Encrypt Plaintext using Key square or Key Matrix

现在,我们将深入探讨如何使用Python3编写上述算法。 我将对算法进行3个步骤的说明,就像我对算法所做的那样。 三个步骤如下:1。 将纯文本分成成对的文本2。 生成密钥矩阵或密钥Square3。 使用密钥平方或密钥矩阵加密纯文本

1.将纯文本分成几对文本。 (1.Separate the Plaintext into pairs of text.)

def plainTextConversion(s,key):
i = 0
sList = list(s.strip())
n = len(sList)
while(n>0):
temp=[]
checkSame=False
#print(sList,'sList')
for j in range(0,2):
if j<len(sList) and sList[j] not in temp :
temp.append(sList[j])
checkSame = False
elif j<len(sList) and sList[j] in temp :
temp.append('x')
checkSame = True
else:
checkSame = False
continue
#print(temp,'temp')
sList.remove(sList[0])
# print(checkSame)
if len(temp)>1 and checkSame == False:
sList.remove(sList[0])
plainText.append(temp)
n=n-2
elif len(temp)>1 and checkSame == True:
#do noting
plainText.append(temp)
n=n-1
elif len(temp)<1 and checkSame == True:
# do nothing
plainText.append(temp)
else:
temp.append('x')
plainText.append(temp)
n=n-2
#print(n,'n')
#print(plainText,'plainText')
print(plainText,'final')
res = playFairCipher(plainText,key)
return res
if __name__ == '__main__':s = input ('enter plainText : ')
key = input('enter key text : ')
s = ''.join(s.split())
key = ''.join(key.split())
print(s,'[s]')
result = plainTextConversion(s,key)
print (result)

Here, In this code I get key and plaiText as Input and remoe the whitespace using join() and split() function. I have created tempList to store the plaintext pairs and then in while loop I am checking repeated characters are present in the message and whether every pair has two letters or at end any letter is left alone so that we can insert filler and All the rules listed in the Step 1.

在这里,在此代码中,我将key和plaiText作为输入,并使用join()和split()函数删除空格。 我创建了tempList来存储明文对,然后在while循环中,我检查消息中是否存在重复的字符,以及每对是否有两个字母还是最后一个字母都没有留下,以便我们可以插入填充符和列出的所有规则在步骤1中。

Next checksame is used to check whether letters in a pair is same or not, if they are same then insert filler x. And also I removed the letter from the list which are checked and converted into pair of list, so it will be bit easier for me to code and I don’t need to use nested for loops . After checking the conditions I appended the temp which contains the pair to plainText List.Now Step 1 is completed.

下一个checksame用于检查一对中的字母是否相同,如果相同,则插入填充符x。 而且我还从列表中删除了已检查并转换为列表对的字母,因此对我来说编码起来会更容易一些,并且不需要使用嵌套的for循环。 检查完条件后,我将包含该对的temp追加到plainText List。现在,步骤1已完成。

2.生成密钥矩阵或密钥平方 (2. Generate Key Matrix or Key Square)

plainText=[]
keyMatrix = []
cipherTextList =[]def index_2d(keyMatrix, v):
for i, x in enumerate(keyMatrix):
if v in x:
return [i, x.index(v)]
def keyMatrixGeneration(keyMatrix,reducedAlphabet):
alphacounter = 0
alpha = len(reducedAlphabet)
#print(alpha,'[alpha]')
while alphacounter < alpha and len(reducedAlphabet[alphacounter:alphacounter+5]) :
tempReducedAlphabet = []
#print(reducedAlphabet[0:5],'[reducedAlphabet temp]')
tempReducedAlphabet.append(reducedAlphabet[alphacounter:alphacounter+5])
alphacounter+=5
keyMatrix.extend(tempReducedAlphabet)
if alphacounter > alpha and len(reducedAlphabet[alphacounter-5:]):
tempReducedAlphabet = []
tempReducedAlphabet.append(reducedAlphabet[alphacounter-5:])
keyMatrix.append(tempReducedAlphabet)
return keyMatrix
def playFairCipher(plainText,key):
# create key matrix
#print(key,'[key]')
#print('[playFairCipher def]')
cipherText = ''
keyList = list(key.strip(' '))
keyListSet = set(keyList) # use this to find difference in alphabet and key
reducedKeyList = []
for ch in keyList:
if ch not in reducedKeyList:
reducedKeyList.append(ch)
tempKey = []
#print(keyListSet,reducedKeyList)
k = len(reducedKeyList)
counter = 0
alphabet = list('abcdefghijklmnopqrstuvwxyz')
alphabetSet = set(alphabet)
keycount = 5
#print(k)
if k==5:
#print('k==5')
keyMatrix.append(reducedKeyList[0:5])
elif k>5:
while keycount<=k:
keyMatrix.append(reducedKeyList[keycount-5:keycount])
keycount+=5
if keycount > k:
keyMatrix.append(reducedKeyList[keycount-5:])
else:
keyMatrix.append(reducedKeyList)
print(keyMatrix,'[before keyMatrix]')
reducedAlphabetSet = alphabetSet-keyListSet
#print(reducedAlphabetSet,'[reducedAlphabetSet]')
reducedAlphabet = list(reducedAlphabetSet)
reducedAlphabet.sort()
#print(reducedAlphabet,'[reducedAlphabet list]')
if 'i'and 'j' in reducedAlphabet:
reducedAlphabet.remove('j')
if 'i' not in reducedAlphabet and 'j' not in reducedAlphabet:
ind = index_2d(keyMatrix,'j')
print(ind,keyMatrix[ind[0]][ind[1]])
keyMatrix[ind[0]].remove(keyMatrix[ind[0]][ind[1]])
lengthCheck = False
keyN = 0
# generation of key matrix
for i in range(0,len(keyMatrix)):
if len(keyMatrix[i])<5:
lengthCheck=True
keyN = i
if lengthCheck==True:
tempReducedAlphabet = []
tempReducedAlphabet.extend(reducedAlphabet[0:5-len(keyMatrix[keyN])])
#print(tempReducedAlphabet,'[tempReducedAlphabet]')
keyMatrix[keyN].extend(tempReducedAlphabet)
for i in tempReducedAlphabet:
reducedAlphabet.remove(i)
#print(reducedAlphabet,'[reducedAlphabet]')
keyMatrixGeneration(keyMatrix,reducedAlphabet)
else:
keyMatrixGeneration(keyMatrix,reducedAlphabet)
print(keyMatrix,'[keymatrix]')

For me this is the most tedious part I struggled a bit in this. This code has two functions playFairCipher and keyMatrixGeneration.

对我来说,这是我为此付出的最繁琐的部分。 此代码具有两个函数playFairCipher和keyMatrixGeneration。

First In playFairCipher I reduced the key i.e removed repeated characters using set datatype so KeyListSet is our reduced KeyList which has alphabet only one time no repeated characters and using Set Difference I am going remove the alphabets that are present in key already and sort them in lexicographical order using list sort method beacause set is unindexed datatype so after converting the difference i.e reducedAlphabet into list. If both I and J present in reducedAlphabet if present I removed ‘j’and if ‘i’ and ‘j’ both are present in keyList I removed ‘j’. This is not a problem if you follow the same while decryption only one rule it should be ‘i’ or ‘j’ not both.

首先在playFairCipher中,我减少了键,即使用set数据类型删除了重复的字符,因此KeyListSet是我们的减少后的KeyList,它只有一次没有重复的字符,并且使用Set Difference,我将删除键中已经存在的字母并按字典顺序进行排序使用列表排序方法的顺序是因为集合是未索引的数据类型,所以在将差异(即reduceAlphabet)转换为列表之后。 如果I和J都出现在reduceedAlphabet中(如果存在),我删除了“ j”,并且如果“ i”和“ j”都存在于keyList中,则删除了“ j”。 如果您遵循相同的规则,而仅解密一个规则,则该规则应该是“ i”或“ j”,而不是两者,所以这不是问题。

After removing the repeated characters and all other things I used some logic to append the these alphabets to the keyMatrix. If the keyList length is not divisible by 5 then the last row’s length will be less than 5 , So from there we have to start extend the list.

除去重复的字符和所有其他内容后,我使用了一些逻辑将这些字母追加到keyMatrix。 如果keyList的长度不能被5整除,那么最后一行的长度将小于5,因此我们必须从那里开始扩展列表。

KeyMatrixGeneration function is all about appending the alphabet since the size is constant I appended 5 alphabet at a time.With This code you will be able to create Key Matrix/ Key Square. Now, we entered the last step. Last but not least the real encryption happens with step 3.

KeyMatrixGeneration函数主要用于附加字母,因为大小是恒定的,我一次附加5个字母。使用此代码,您可以创建Key Matrix / Key Square。 现在,我们进入了最后一步。 最后但并非最不重要的一点是,真正的加密发生在步骤3中。

3.使用密钥平方或密钥矩阵对纯文本进行加密 (3. Encrypt Plaintext using Key square or Key Matrix)

# matching plainText with key matrix
for i in range(0,len(plainText)):
first=[]
second=[]
first.extend(index_2d(keyMatrix,plainText[i][0]))
second.extend(index_2d(keyMatrix,plainText[i][1]))
if first[0]!=second[0] and first[1]!=second[1]:
cipherText += keyMatrix[first[0]][second[1]]+ keyMatrix[second[0]][first[1]]
elif first[0]==second[0]:
if first[1]+1<len(keyMatrix[first[0]]):
cipherText+=keyMatrix[first[0]][first[1]+1]
else:
cipherText+=keyMatrix[first[0]][0]
if second[1]+1<len(keyMatrix[second[0]]):
cipherText+=keyMatrix[first[0]][second[1]+1]
else:
cipherText+=keyMatrix[first[0]][0]
else:
if first[0]+1<len(keyMatrix):
cipherText+=keyMatrix[first[0]+1][first[1]]
else:
cipherText+=keyMatrix[0][first[1]]
if second[0]+1<len(keyMatrix):
cipherText+=keyMatrix[second[0]+1][second[1]]
else:
cipherText+=keyMatrix[0][second[1]]
#print(first,'[first]')
print(cipherText,'[cipherText]')
return cipherText

Add this code at the end of the PlayFairCipher function. In this I used if and else condition to check whether they are in same or in different row or same column or different column using index_2d function which is already present in step 2. For your reference I will write the index_2d function code here.

在PlayFairCipher函数的末尾添加此代码。 在这种情况下,我使用if和else条件使用步骤2中已经存在的index_2d函数检查它们是否在相同或不同的行,相同的列或不同的列中。供您参考,我将在此处编写index_2d函数代码。

def index_2d(keyMatrix, v):
for i, x in enumerate(keyMatrix):
if v in x:
return [i, x.index(v)]

It takes the list in which value to be found and the value to be found as arguments. It returns the indices of the value. First represent first letter in the pair and second represent second in the pair. With these value I progammed the rules that I said while explaining the algorithm Step 3 feel free to read those rules again if you feel like you don’t understand the code.

它使用要在其中找到值和要找到的值的列表作为参数。 它返回值的索引。 第一个代表该对中的第一个字母,第二个代表该对中的第二个字母。 凭借这些价值,我对我在解释算法时所说的规则进行了编程,如果您觉得自己不懂代码,则可以再次阅读这些第3步规则。

Hurray! You have learned how to program PlayFairCipher Encryption Using Python 3.Below is the entire Code of PlayFairCipher Encryption.

欢呼! 您已经了解了如何使用Python 3编程PlayFairCipher加密。下面是PlayFairCipher加密的完整代码。

plainText=[]
keyMatrix = []
cipherTextList =[]def index_2d(keyMatrix, v):
for i, x in enumerate(keyMatrix):
if v in x:
return [i, x.index(v)]
def keyMatrixGeneration(keyMatrix,reducedAlphabet):
alphacounter = 0
alpha = len(reducedAlphabet)
#print(alpha,'[alpha]')
while alphacounter < alpha and len(reducedAlphabet[alphacounter:alphacounter+5]) :
tempReducedAlphabet = []
#print(reducedAlphabet[0:5],'[reducedAlphabet temp]')
tempReducedAlphabet.append(reducedAlphabet[alphacounter:alphacounter+5])
alphacounter+=5
keyMatrix.extend(tempReducedAlphabet)
if alphacounter > alpha and len(reducedAlphabet[alphacounter-5:]):
tempReducedAlphabet = []
tempReducedAlphabet.append(reducedAlphabet[alphacounter-5:])
keyMatrix.append(tempReducedAlphabet)
return keyMatrix
def playFairCipher(plainText,key):
# create key matrix
#print(key,'[key]')
#print('[playFairCipher def]')
cipherText = ''
keyList = list(key.strip(' '))
keyListSet = set(keyList) # use this to find difference in alphabet and key
reducedKeyList = []
for ch in keyList:
if ch not in reducedKeyList:
reducedKeyList.append(ch)
tempKey = []
#print(keyListSet,reducedKeyList)
k = len(reducedKeyList)
counter = 0
alphabet = list('abcdefghijklmnopqrstuvwxyz')
alphabetSet = set(alphabet)
keycount = 5
#print(k)
if k==5:
#print('k==5')
keyMatrix.append(reducedKeyList[0:5])
elif k>5:
while keycount<=k:
keyMatrix.append(reducedKeyList[keycount-5:keycount])
keycount+=5
if keycount > k:
keyMatrix.append(reducedKeyList[keycount-5:])
else:
keyMatrix.append(reducedKeyList)
print(keyMatrix,'[before keyMatrix]')
reducedAlphabetSet = alphabetSet-keyListSet
#print(reducedAlphabetSet,'[reducedAlphabetSet]')
reducedAlphabet = list(reducedAlphabetSet)
reducedAlphabet.sort()
#print(reducedAlphabet,'[reducedAlphabet list]')
if 'i'and 'j' in reducedAlphabet:
reducedAlphabet.remove('j')
if 'i' not in reducedAlphabet and 'j' not in reducedAlphabet:
ind = index_2d(keyMatrix,'j')
print(ind,keyMatrix[ind[0]][ind[1]])
keyMatrix[ind[0]].remove(keyMatrix[ind[0]][ind[1]])
lengthCheck = False
keyN = 0
# generation of key matrix
for i in range(0,len(keyMatrix)):
if len(keyMatrix[i])<5:
lengthCheck=True
keyN = i
if lengthCheck==True:
tempReducedAlphabet = []
tempReducedAlphabet.extend(reducedAlphabet[0:5-len(keyMatrix[keyN])])
#print(tempReducedAlphabet,'[tempReducedAlphabet]')
keyMatrix[keyN].extend(tempReducedAlphabet)
for i in tempReducedAlphabet:
reducedAlphabet.remove(i)
#print(reducedAlphabet,'[reducedAlphabet]')
keyMatrixGeneration(keyMatrix,reducedAlphabet)
else:
keyMatrixGeneration(keyMatrix,reducedAlphabet)
print(keyMatrix,'[keymatrix]')
# matching plainText with key matrix
for i in range(0,len(plainText)):
first=[]
second=[]
first.extend(index_2d(keyMatrix,plainText[i][0]))
second.extend(index_2d(keyMatrix,plainText[i][1]))
if first[0]!=second[0] and first[1]!=second[1]:
cipherText += keyMatrix[first[0]][second[1]]+ keyMatrix[second[0]][first[1]]
elif first[0]==second[0]:
if first[1]+1<len(keyMatrix[first[0]]):
cipherText+=keyMatrix[first[0]][first[1]+1]
else:
cipherText+=keyMatrix[first[0]][0]
if second[1]+1<len(keyMatrix[second[0]]):
cipherText+=keyMatrix[first[0]][second[1]+1]
else:
cipherText+=keyMatrix[first[0]][0]
else:
if first[0]+1<len(keyMatrix):
cipherText+=keyMatrix[first[0]+1][first[1]]
else:
cipherText+=keyMatrix[0][first[1]]
if second[0]+1<len(keyMatrix):
cipherText+=keyMatrix[second[0]+1][second[1]]
else:
cipherText+=keyMatrix[0][second[1]]
#print(first,'[first]')
print(cipherText,'[cipherText]')
return cipherText
def plainTextConversion(s,key):
i = 0
sList = list(s.strip())
n = len(sList)
while(n>0):
temp=[]
checkSame=False
#print(sList,'sList')
for j in range(0,2):
if j<len(sList) and sList[j] not in temp :
temp.append(sList[j])
checkSame = False
elif j<len(sList) and sList[j] in temp :
temp.append('x')
checkSame = True
else:
checkSame = False
continue
#print(temp,'temp')
sList.remove(sList[0])
# print(checkSame)
if len(temp)>1 and checkSame == False:
sList.remove(sList[0])
plainText.append(temp)
n=n-2
elif len(temp)>1 and checkSame == True:
#do noting
plainText.append(temp)
n=n-1
elif len(temp)<1 and checkSame == True:
# do nothing
plainText.append(temp)
else:
temp.append('x')
plainText.append(temp)
n=n-2
#print(n,'n')
#print(plainText,'plainText')
print(plainText,'final')
res = playFairCipher(plainText,key)
return res
if __name__ == '__main__':s = input ('enter plainText : ')
key = input('enter key text : ')
s = ''.join(s.split())
key = ''.join(key.split())
print(s,'[s]')
result = plainTextConversion(s,key)
print (result)

This is all. I hope you Understand this code .

这就是全部。 希望您理解此代码。

Happy coding 😄

快乐编码😄

Coding is addictive fun too

编码也是令人上瘾的乐趣

翻译自: https://medium.com/analytics-vidhya/play-fair-cipher-encryption-using-python3-f91c42931f52

python 密码加密

如果您想加密一个文件夹或zip文件,可以使用Python中的加密库来实现。以下是一些常用的加密库: 1. pyAesCrypt:这是一个用于加密和解密文件的Python库。它使用AES加密算法,并且可以处理大文件。 2. cryptography:这是一个用于加密和解密数据的Python库。它支持多种加密算法,包括AES、DES、RSA等。 3. PyCrypto:这是一个Python密码库,支持多种加密算法,包括AES、DES、RSA、Blowfish等。 下面是使用pyAesCrypt加密文件夹或zip文件的代码示例: ```python import pyAesCrypt import os # 定义加密函数 def encrypt_folder(password, src_folder, dest_zip): bufferSize = 64 * 1024 pyAesCrypt.encryptFile(src_folder, dest_zip, password, bufferSize) # 定义解密函数 def decrypt_folder(password, src_zip, dest_folder): bufferSize = 64 * 1024 pyAesCrypt.decryptFile(src_zip, dest_folder, password, bufferSize) # 加密文件夹 password = "mypassword" src_folder = "myfolder" dest_zip = "myfolder.zip" encrypt_folder(password, src_folder, dest_zip) # 解密文件夹 src_zip = "myfolder.zip" dest_folder = "myfolder_decrypted" decrypt_folder(password, src_zip, dest_folder) ``` 在上面的代码中,我们使用pyAesCrypt库来加密和解密文件夹。首先,我们定义了两个函数:encrypt_folder和decrypt_folder,分别用于加密和解密文件夹。接着,我们定义了一个密码变量和两个文件路径变量,用于指定要加密的文件夹和加密后的zip文件。最后,我们调用encrypt_folder函数来加密文件夹,调用decrypt_folder函数来解密文件夹。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值