'Is my method to use eval() safe? I think it can dodge a security breach via code-injection. Any Objections?

My Method: Create a whitelist (valid input), define a variable to user-input, check every index (element of user-input-string) if its in the whitelist with loop + counter. If its all valid, the last if-statement (all_valid) runs, in which the eval()-function will be executed, not before (1. Validation => 2. Execute eval()). The print-command are optional and only to check if the validation-process works.

while True:
    whitelist = ["+","-","4","2"]
    user_input = input(":> ")
    counter = 0
    all_valid = 0
    
    validation_loop = True
    while validation_loop:
        if len(user_input) == counter:
            all_valid = 1
            break
        if user_input[counter] in whitelist: 
            print("Valid Element")
        else:
            print("Invalid Element"); break
        counter += 1

    if all_valid == 1:
        print(eval(user_input))



Solution 1:[1]

This works, but you can do it in fewer lines

if len([i for i in user_input if i in whitelist]) == len(user_input):
    print(eval(user_input))
else:
    print("Invalid input")

But I think you should just avoid using the eval function in general, interpret it on your own if it's just a calculator.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ayza