前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >加密算法实例:替换密码

加密算法实例:替换密码

原创
作者头像
软件架构师Michael
发布2025-02-11 14:18:12
发布2025-02-11 14:18:12
9200
代码可运行
举报
运行总次数:0
代码可运行

加密函数:

代码语言:python
代码运行次数:0
复制
def simple_sub_cipher(text, substitution_map):
    encrypted_text = []
    plaintext_length = len(text)
    
    for i in range(plaintext_length):
        if text[i] in substitution_map:
            encrypted_text.append(substitution_map[text[i]])
        else:
            encrypted_text.append(text[i])
    return ''.join(encrypted_text)

def main():
    plain_text = 'Hello, World!'
    cipher_text = simple_sub_cipher(plain_text, substitution_map)
    
    print("Plaintext:", plain_text)
    print("Ciphertext:", cipher_text)
    decrypted_text = simple_sub_cipher(cipher_text, substitution_map)
    print("Decrypted Plaintext:", decrypted_text)

# 加密映射
substitution_map = {
    'A': 'Z',
    'B': 'Y',
    'C': 'X',
    'D': 'W',
    'E': 'V',
    'F': 'U',
    'G': 'T',
    'H': 'S',
    'I': 'R',
    'J': 'Q',
    'K': 'P',
    'L': 'O',
    'M': 'N',
    'O': 'M',
    'P': 'L',
    'Q': 'K',
    'R': 'J',
    'S': 'I',
    'T': 'H',
    'U': 'G',
    'V': 'F',
    'W': 'E',
    'X': 'D',  # 需要替换所有非字母字符
    'Y': 'C',
    'Z': 'B'
}

解密函数:

代码语言:python
代码运行次数:0
复制
def simple_sub_decipher(ciphertext, substitution_map):
    decrypted_text = []
    ciphertext_length = len(ciphertext)
    
    for i in range(ciphertext_length):
        if ciphertext[i] in substitution_map:
            decrypted_text.append(substitution_map[ciphertext[i]])
        else:
            decrypted_text.append(ciphertext[i])
    return ''.join(decrypted_text)

以上加密算法,配备了相应的解密函数。必要时可以参考。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档