关键词:encryption

加密过程:

  1. 去除第一次出现之外的所有相同字母,得到关键词 "encrypti"
  2. 将明文转换成小写,并去除空格和标点符号
  3. 将明文中的每个字母替换成关键词中对应位置的字母
  4. 得到密文

解密过程:

  1. 去除第一次出现之外的所有相同字母,得到关键词 "encrypti"
  2. 将密文中的每个字母替换成关键词中对应位置的字母
  3. 得到明文

下面是Python代码实现:

def remove_duplicate(keyword):
    # 去除第一次出现之外的所有相同字母
    new_keyword = []
    for letter in keyword:
        if letter not in new_keyword:
            new_keyword.append(letter)
        else:
            continue
    return ''.join(new_keyword)

def encrypt(plaintext, keyword):
    # 去除重复字母
    keyword = remove_duplicate(keyword)
    # 将明文转换成小写,并去除空格和标点符号
    plaintext = ''.join(filter(str.isalpha, plaintext)).lower()
    # 将明文中的每个字母替换成关键词中对应位置的字母
    ciphertext = ''
    for letter in plaintext:
        if letter in keyword:
            index = keyword.index(letter)
            ciphertext += keyword[index]
        else:
            ciphertext += letter
    return ciphertext

def decrypt(ciphertext, keyword):
    # 去除重复字母
    keyword = remove_duplicate(keyword)
    # 将密文中的每个字母替换成关键词中对应位置的字母
    plaintext = ''
    for letter in ciphertext:
        if letter in keyword:
            index = keyword.index(letter)
            plaintext += chr(ord('a') + index)
        else:
            plaintext += letter
    return plaintext

# 测试代码
keyword = 'encryption'
plaintext = 'This is a secret message!'
ciphertext = encrypt(plaintext, keyword)
print(ciphertext) # 输出:bhy hy e ycnhti cyhhbt!

decrypted_text = decrypt(ciphertext, keyword)
print(decrypted_text) # 输出:this is a secret message!
``
1、选择一个关键词如果这个关键词中有重复的字母则去除第一次出现之外的所有相同字母。写一个这个Python加密和解码程序

原文地址: https://www.cveoy.top/t/topic/hjbU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录