【问题标题】:Creating an Ascii encryption function in python, advice?在 python 中创建一个 Ascii 加密函数,建议?
【发布时间】:2017-03-11 21:08:00
【问题描述】:

我正在尝试使用以下函数在 Python 中创建加密函数。

def code_char(c, key):
    adj = ord('a') if c.islower() else ord('A') 
    return chr(adj + (ord(c)-adj+int(key))%26)

^编码一个字符

def isletter(c):
    if 65 <= ord(c) <= 90:
        return True
    elif 97 <= ord(c) <= 122:
        return True
    else:
        return False

^检查字符是否为字母

加密函数必须包含code_blockisletter(c)函数

我希望能够输入任何长度的字符串,它会根据 8 位密钥对其进行加密。

我还希望它忽略任何空格、标点符号和任何不是字母的内容。

任何帮助将不胜感激

【问题讨论】:

    标签: python python-3.x encryption ascii


    【解决方案1】:

    您的问题在于 code_char,因为当您添加 int(key) 时,您需要修改 %26 以确保字母保持为 ascii 字符:

    def code_char(c, key):
        adj = ord('a') if c.islower() else ord('A')
        return chr(adj + (ord(c)-adj+int(key))%26)
    

    结果:

    >>> encrypt("This is  a   secret  message!!", "12345678")
    'Ujlw ny  h   afeuiy  slatcji!!'
    

    你当然可以改进你的代码,例如你的code_block可以被重写:

    import itertools as it
    
    def code_block(word, key):
        k = it.cycle(key)
        return "".join(code_char(c, next(k)) if isletter(c) else c for c in word)
    

    你也可以重写你的isletter():

    def isletter(c):
        return c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    

    您可以利用已经定义了这个的string 模块:

    import string
    def isletter(c):
        return c in string.ascii_letters
    

    最后,您的encrypt() 不必要地创建了一个列表和''.join(),只是:

    def encrypt(s, key):   # string is a module - may clash
        return code_block(s, key)
    

    注意:if 65 &lt;= ord(c) &lt;= 90: 是完全合法的,并且可以在 Python 中执行您期望它执行的操作。

    【讨论】:

    • 我现在需要写反对 code_char decode_char 我要反转 code_char 函数的符号吗?我正在尝试,但我没有尝试给我This is a secret message!!???
    • -int(key)
    【解决方案2】:

    isletter做了一些改变

    def isletter(c):
        if 65 <= ord(c) and ord(c) <= 90:
            return True
        elif 97 <= ord(c) and ord(c) <= 122:
            return True
        else:
            return False
    

    在您的旧代码中:

    65<=ord(c)<=90
    

    65&lt;=ord(c) 将给出一些布尔值,然后将其与90 进行比较。 [AC:在 python 中不正确]

    code_char功能变化:

    def code_char(c, key):
        tmp=ord(c)+int(key)
        if(tmp>122):
            return chr(tmp-26)
        else:
            return chr(tmp) 
    

    【讨论】:

    • 这给出了无效的语法消息?
    • 它不在shell中,当我按F5运行程序时,弹出一个窗口说语法无效,第二个&突出显示为红色
    • 有什么变化?
    • 当你添加字符和数字时,它们有可能变成非字母。
    • 如何防止这种情况并让它回到字母表的开头?
    猜你喜欢
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2014-01-23
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多