Autokey加密是一种基于密钥自动重复的加密技术,在加密和解密时需要使用到同一个密钥。以下是Python中实现Autokey加密的示例代码:
def autokey_encrypt(plaintext, key):
key = key.upper()
key_chars = [i for i in key if i.isalpha()]
ciphertext = ""
key_index = 0
for char in plaintext.upper():
if char.isalpha():
shift = ord(key_chars[key_index]) - ord('A')
cipher_char = chr(((ord(char) - ord('A') + shift) % 26) + ord('A'))
ciphertext += cipher_char
key_index = (key_index + 1) % len(key_chars)
else:
ciphertext += char
return ciphertext
def autokey_decrypt(ciphertext, key):
key = key.upper()
key_chars = [i for i in key if i.isalpha()]
plaintext = ""
key_index = 0
for char in ciphertext.upper():
if char.isalpha():
shift = ord(key_chars[key_index]) - ord('A')
plain_char = chr(((ord(char) - ord('A') - shift) % 26) + ord('A'))
plaintext += plain_char
key_chars.append(plain_char)
key_index = (key_index + 1) % len(key_chars)
else:
plaintext += char
return plaintext
使用方法如下:
plaintext = "ATTACKATDAWN"
key = "LEMON"
ciphertext = autokey_encrypt(plaintext, key)
print(ciphertext) # LXFOPVEFRNHR
decrypted_text = autokey_decrypt(ciphertext, key)
print(decrypted_text) # ATTACKATDAWN