下美:Vigenere算法你知道吗,小可。小可!小可!醒醒!信息课上还敢睡!
小可:哦!(揉了揉眼睛)
下美:Vigenere算法实现加密和解密你知道吗?
小可:python写的吗?
下美:对啊!
小可:哈!我会!
信息课老师:你么两干啥呢?
下美:呃……是……
小可:哈哈,是py写的Vigenere算法实现加密和解密。
信息课老师:代码给我看看。
小可:
def encrypt(plaintext, key):
ciphertext = ""
key_index = 0
for char in plaintext:
if char.isalpha():
shifted = (ord(char.upper()) + ord(key[key_index].upper()) - 2 * ord('A')) % 26
if char.islower():
ciphertext += chr(shifted + ord('a'))
else:
ciphertext += chr(shifted + ord('A'))
key_index = (key_index + 1) % len(key)
else:
ciphertext += char
return ciphertext
def decrypt(ciphertext, key):
plaintext = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
shifted = (ord(char.upper()) - ord(key[key_index].upper()) + 26) % 26
if char.islower():
plaintext += chr(shifted + ord('a'))
else:
plaintext += chr(shifted + ord('A'))
key_index = (key_index + 1) % len(key)
else:
plaintext += char
return plaintext
plain_text = input("请输入待加密的文本: ")
keyword = input("请输入加密关键词: ")
encrypted_text = encrypt(plain_text, keyword)
print("加密后的文本: ", encrypted_text)
decrypted_text = decrypt(encrypted_text, keyword)
print("解密后的文本: ", decrypted_text)
下美:完美啊!
信息课老师:呃……厉害!(心里其实想的:我刚想抄小可呢,睡觉!)
信息课老师:试一下!
小可:
信息课老师: 好吧。
下美,小可:醒醒老师!