温馨提示×

python简单加密算法怎么写

小亿
85
2023-12-13 14:12:24
栏目: 编程语言

Python中的简单加密算法可以使用替换或移位等操作来实现。下面是一个使用替换操作的简单加密算法示例:

def encrypt(message):
    # 定义替换规则
    substitution = {
        'a': 'b',
        'b': 'c',
        'c': 'd',
        'd': 'e',
        'e': 'f',
        'f': 'g',
        'g': 'h',
        'h': 'i',
        'i': 'j',
        'j': 'k',
        'k': 'l',
        'l': 'm',
        'm': 'n',
        'n': 'o',
        'o': 'p',
        'p': 'q',
        'q': 'r',
        'r': 's',
        's': 't',
        't': 'u',
        'u': 'v',
        'v': 'w',
        'w': 'x',
        'x': 'y',
        'y': 'z',
        'z': 'a'
    }
    
    encrypted_message = ''
    for char in message:
        if char.lower() in substitution:
            # 将字符替换为对应的加密字符
            encrypted_message += substitution[char.lower()]
        else:
            encrypted_message += char  # 如果字符不在替换规则中,则保持原样
    
    return encrypted_message

message = input('请输入需要加密的消息:')
encrypted_message = encrypt(message)
print('加密后的消息:', encrypted_message)

在这个示例中,使用了一个简单的替换规则将字母替换为其后一位字母,即’a’替换为’b’,‘b’替换为’c’,依此类推。输入的消息中出现的字母都会被替换为对应的加密字符,其他字符保持不变。

0