意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

Python仿射密码的实现和单字母密码用法是什么

来源:恒创科技 编辑:恒创科技编辑部
2023-12-30 21:43:59
今天这篇我们来学习和了解“Python仿射密码的实现和单字母密码用法是什么”,下文的讲解详细,步骤过程清晰,对大家进一步学习和理解“Python仿射密码的实现和单字母密码用法是什么”有一定的帮助。有这方面学习需要的朋友就继续往下看吧!


Python仿射密码的实现和单字母密码用法是什么


仿射密码

Affine Cipher是Multiplicative Cipher和Caesar Cipher算法的组合.

仿射密码的基本实现如下图所示 :

我们将通过创建包含两个加密和解密基本函数的相应类来实现仿射密码.

代码

您可以使用以下代码实现仿射密码 :

class仿射(对象):
DIE=128
KEY=(7,3,55)
def__init__(self):
#传递
defencryptChar(self,char):
K1,K2,kI=self.KEY
returnchr((K1*ord(char)+K2)%self.DIE)
defencrypt(self,string):
return"".join(map(self.encryptChar,string))
defdecryptChar(self,char):
K1,K2,KI=self.KEY
returnchr(KI*(ord(char)-K2)%self.DIE)
defdecrypt(self,string):
return"".join(map(self.decryptChar,string))
affine=Affine()
printaffine.encrypt('AffineCipher')
printaffine.decrypt('*18?FMT')

输出

实现仿射密码时,可以观察到以下输出;

输出显示纯文本消息仿射密码的加密消息和已作为输入abcdefg发送的消息的解密消息.

单字母密码

接下来,您将学习使用Python的单字母密码及其黑客攻击.

单字母密码使用固定替换用于加密整个消息.这里显示使用带有JSON对象的Python字典的单字母密码 :

monoalpha_cipher={
'a':'m',
'b':'n',
'c':'b',
'd':'v',
'e':'c',
'f':'x',
'g':'z',
'h':'a',
'i':'s',
'j':'d',
'k':'f',
'l':'g',
'm':'h',
'n':'j',
'o':'k',
'p':'l',
'q':'p',
'r':'o',
's':'i',
't':'u',
'u':'y',
'v':'t',
'w':'r',
'x':'e',
'y':'w',
'z':'q',
'':'',
}

借助此词典,我们可以使用相关字母加密字母为JSON对象中的值.

以下程序创建一个单字母程序作为类表示,其中包括加密和解密的所有功能.

fromstringimportletters,digits
fromrandomimportshuffle
defrandom_monoalpha_cipher(pool=None):
ifpoolisNone:
pool=letters+digits
original_pool=list(pool)
shuffled_pool=list(pool)
shuffle(shuffled_pool)
returndict(zip(original_pool,shuffled_pool))
definverse_monoalpha_cipher(monoalpha_cipher):
inverse_monoalpha={}
forkey,valueinmonoalpha_cipher.iteritems():
inverse_monoalpha[value]=key
returninverse_monoalpha
defencrypt_with_monoalpha(message,monoalpha_cipher):
encrypted_message=[]
forletterinmessage:
encrypted_message.append(monoalpha_cipher.get(letter,letter))
return''.join(encrypted_message)
defdecrypt_with_monoalpha(encrypted_message,monoalpha_cipher):
returnencrypt_with_monoalpha(
encrypted_message,
inverse_monoalpha_cipher(monoalpha_cipher)
)

稍后调用此文件以实现Monoalphabetic密码的加密和解密过程,如下所示 :

importmonoalphabeticCipherasmc
cipher=mc.random_monoalpha_cipher()
print(cipher)
encrypted=mc.encrypt_with_monoalpha('Helloallyouhackersoutthere!',cipher)
decrypted=mc.decrypt_with_monoalpha('sXGGtSGGNt0HSrLXFCt0UUHXFX!',cipher)
print(encrypted)
print(decrypted)

输出

当您实现上面给出的代码时,您可以观察到以下输出;

T嗯,你可以用一个指定的键值对来破解单字母密码,这会将密文破解成实际的纯文本.


这篇关于“Python仿射密码的实现和单字母密码用法是什么”的文章就介绍到这了,更多相关的内容,欢迎关注恒创科技,小编将为大家输出更多高质量的实用文章!
上一篇: Python base64编码作用是什么,如何执行base64编码 下一篇: Python XOR算法有什么好处,XOR过程是怎样的