affineCipher

PY #仿射密码#http://inventwithpython.com/hacking (BSD许可)进口SYS,pyperclip,cryptomath,随机符号= “” #$%&'()* +, “!” - 。/ 0123456789 :; <=>?@ ABCDEFGHIJKLMNOPQRSTUVWXYZ [\] ^ _ abcdefghijklmnopqrstuvwxyz {|}〜“”“#注意前面的空格”“”字符串也叫多行字符串def main(): myMessage =“”“ “计算机应该被称为智能,如果它可以欺骗人类相信它是人类。” - Allan Turing“”“ myKey = 2023#可以调整为getRandomKey,随机获取秘 钥KEY myMode =‘encrypt’#set 如果myMode ==‘encrypt’ ,则’加密’或’解密’: translated = encryptMessage(myKey,myMessage) elif myMode ==‘decrypt’:

    translated = decryptMessage(myKey, myMessage)
print('Key: %s' % (myKey))
print('%sed text:' % (myMode.title()))
print(translated)
pyperclip.copy(translated)
print('Full %sed text copied to clipboard.' % (myMode))

def getKeyParts(key):
keyA = key // len(SYMBOLS)
keyB = key % len(SYMBOLS)
return (keyA, keyB)

def checkKeys(keyA, keyB, mode):
if keyA == 1 and mode == ‘encrypt’:
sys.exit(‘The affine cipher becomes incredibly weak when key A is set to 1. Choose a different key.’)
if keyB == 0 and mode == ‘encrypt’:
sys.exit(‘The affine cipher becomes incredibly weak when key B is set to 0. Choose a different key.’)
if keyA < 0 or keyB < 0 or keyB > len(SYMBOLS) - 1:
sys.exit(‘Key A must be greater than 0 and Key B must be between 0 and %s.’ % (len(SYMBOLS) - 1))
if cryptomath.gcd(keyA, len(SYMBOLS)) != 1:
sys.exit(‘Key A (%s) and the symbol set size (%s) are not relatively prime. Choose a different key.’ % (keyA, len(SYMBOLS)))

def encryptMessage(key, message):
keyA, keyB = getKeyParts(key)
checkKeys(keyA, keyB, ‘encrypt’)
ciphertext = ‘’
for symbol in message:
if symbol in SYMBOLS:
# encrypt this symbol
symIndex = SYMBOLS.find(symbol)#find用来获取索引值
ciphertext += SYMBOLS[(symIndex * keyA + keyB) % len(SYMBOLS)]
else:
ciphertext += symbol # just append this symbol unencrypted
return ciphertext

def decryptMessage(key, message):
keyA, keyB = getKeyParts(key)
checkKeys(keyA, keyB, ‘decrypt’)
plaintext = ‘’
modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))

for symbol in message:
    if symbol in SYMBOLS:
        # decrypt this symbol
        symIndex = SYMBOLS.find(symbol)
        plaintext += SYMBOLS[(symIndex - keyB) * modInverseOfKeyA % len(SYMBOLS)]
    else:
        plaintext += symbol # just append this symbol undecrypted
return plaintext

def getRandomKey(): 而True: keyA = random.randint(2,len(SYMBOLS)) keyB = random.randint(2,len(SYMBOLS)) if cryptomath.gcd(keyA,len(SYMBOLS))== 1: return keyA * len(SYMBOLS)+ keyB#如果运行affineCipher.py(而不是作为模块导入),请调用#the main()函数。如果__ name __ ==’ __ main __ ':main() `

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值