Search code examples
python-3.xreverse-engineering

How can i restrict input characters to just letters


I don't know much about python, I'm studying reverse engineering now, for a training program crackme.exe I found this code on python. please tell me how to check the input characters for numbers - only letters are needed, and numbers must be excluded or output " input error"

def keygen(name):   
    word = 0          
    for letter in name:   
        word += ord(letter)
    
    return word ^ 0x5678 ^ 0x1234 
    

import sys   

if __name__ == '__main__':   
    if len(sys.argv) < 2:   
        print("Name")
        sys.exit(1)
    else:
        print(keygen(sys.argv[1].upper()))  


sys.argv
sys.exit(1)

Solution

  • You could iterate over each character of the input string and check if is a letter in the alphabet.

    I've created a function below called is_valid which should solve your problem. If you want to change which characters are valid, you can do so by editing the alphabet variable.

    alphabet = "abcdefghijklmnopqrstuvwxyz"
    
    def is_valid(text):
        for char in text:
            # char.lower() makes sure the text is lowercase, otherwise "Hello" would not be valid because capital H wasn't in the alphabet.
            if char.lower() not in alphabet:
                return False
        else: # We've finished iterating, which means all characters were in the alphabet.
            return True
    
    if __name__ == '__main__':   
        if len(sys.argv) < 2:   
            print("Name")
            sys.exit(1)
        else:
            if is_valid(sys.argv[1]): # Yay! Its valid so we can run our function
                print(keygen(sys.argv[1].upper()))
            else:
                sys.exit(1) # Its not valid so we should exit with Code 1