将字符串解密为数字

Nat*_*ler -1 python encryption python-3.x

上周,我被指派将数字PIN加密成可发音的字符串(由元音 - 辅音对组成).这很顺利.

本周,我被指派将我的功能产生的字符串解密回原始的PIN表格.我正在尝试对我的代码进行反向工程,但我不知道从哪里开始.

全局变量:

CONSONANTS = "bcdfghjklmnpqrstvwyz" 
VOWELS = "aeiou" 
Run Code Online (Sandbox Code Playgroud)

加密代码:

def alphapinEncode(pin):
    '''(num) -> string
    Takes user input (pin) and converts it into a pronounceable string.
    Returns the string (codedPin)

    Examples:
    >>> alphainEncode(4327)
    'lohi'
    >>> alphainEncode(3463470)
    'bomejusa'
    '''

    codedPin = ""

    while pin > 0:
        last_two_digits = pin % 100
        codedPin = VOWELS[last_two_digits % 5] + codedPin
        codedPin = CONSONANTS[last_two_digits // 5] + codedPin
        pin = pin // 100

    return codedPin
Run Code Online (Sandbox Code Playgroud)

解密代码:

def alphapinDecode(codedPin):
    '''(string) -> num
    DOCSTRING PLACEHOLDER
    '''

    #This while loop checks validity of input string (string).
    testPin = codedPin
    while len(testPin) > 0:
        if testPin[-1] in VOWELS and testPin[-2] in CONSONANTS:
            testPin = testPin[:-2]
        else:
            print ("Your string is incorrectly formatted. Please use consonant-vowel pairs.")
            return None

    #Decryption code goes here!

    return #pin
Run Code Online (Sandbox Code Playgroud)

Mon*_*pit 5

规范问题:当要解码的字符串长度不均匀时会发生什么?

忽略这种情况,你的方法应该类似于:

  1. codedPin分组分成2组,或从输入中一次取2个字符.保留这些值,以便我们可以解码当前的2组.

  2. 反转用于加密引脚的算法.许多评论都说你不能反转模运算 - 这在通用情况下可能是正确的,但由于我们只处理正整数,我们当然可以扭转价值.这是一个提示:找到index原始字符串CONSONANTSVOWELS字符串中的每个字符,给自己一个数字开始.如果您遇到数学问题,请尝试手动解码一张纸上的一个示例.密切关注字符索引与原始PIN号之间的关系.

  3. 存储每对数字的值,直到到达字符串的末尾.

  4. 返回或输出完整值.

我不会为你编写答案,因为我相信你最好自己想出一些东西.将这些步骤作为指针并开始编码!看看你提出了什么并回来,你会得到一些代码,你可以用来提出实际问题.