简体   繁体   English

使用特定功能的python加密程序

[英]Encryption program with python using a specific function

I'm trying to write a python program that is going to encrypt the user's input message by using an equation that is also given by the user. 我正在尝试编写一个python程序,该程序将通过使用由用户给出的方程式来加密用户的输入消息。 This is going to be my first program (except "hello world" and "number guesser"). 这将是我的第一个程序(“ hello world”和“数字猜测器”除外)。 I'll try to be more specific. 我会尝试更具体。 I think the first thing to do is, creating a list and writing all the letters and their corresponding numbers. 我认为要做的第一件事是创建列表并写出所有字母及其相应的数字。 asking for string input, and asking the user write an equation like 3x+2. 要求输入字符串,并要求用户编写一个等式3x + 2。 What I am trying to do is, for each letter of the string input find the corresponding number from the list and use the equation to produce another output. 我想做的是,对于字符串输入的每个字母,从列表中找到相应的数字,并使用等式生成另一个输出。 I think I should split the message that is going to be encrypted and find the each number values, but how am I gonna make the python put those numbers into the equation? 我想我应该分割将要加密的消息并找到每个数字值,但是我将如何使python将这些数字放入等式中? Thank you for any help 感谢您的任何帮助

You can go char-by-char within a for-loop and use ord() to get the ordinal number of a ascii-character. 您可以在for循环中逐个字符并使用ord()获得ascii字符的序数。 To evaluate arithmetic expressions you might use ast (see Evaluating a mathematical expression in a string ). 要评估算术表达式,您可以使用ast(请参阅评估字符串中的数学表达式 )。 Before that you need to replace "x" with the previously gathered ordinal number. 在此之前,您需要用先前收集的序号替换“ x”。

Here's a minimal example which hopefully does exactly that. 这是一个希望能做到的最小例子。

Usage: 用法:

$ python mycrypt.py "Stack Overflow is Awesome!" "3x+2"
:251:350:293:299:323:98:239:356:305:344:308:326:335:359:98:317:347:98:197:359:305:347:335:329:305:101:

Code: 码:

#!/usr/bin/python
import sys
import ast
import operator as op

# supported operators
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
             ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
             ast.USub: op.neg}

def eval_expr(expr):
    """
    >>> eval_expr('2^6')
    4
    >>> eval_expr('2**6')
    64
    >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
    -5.0
    """
    return eval_(ast.parse(expr, mode='eval').body)

def eval_(node):
    if isinstance(node, ast.Num): # <number>
        return node.n
    elif isinstance(node, ast.BinOp): # <left> <operator> <right>
        return operators[type(node.op)](eval_(node.left), eval_(node.right))
    elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
        return operators[type(node.op)](eval_(node.operand))
    else:
        raise TypeError(node)

# Your first argument (e.g. "Stack Overflow is Awesome!")
text = sys.argv[1]
# Your second argument (e.g. "3x+2")
calc = sys.argv[2]

# Print beginning
sys.stdout.write(":")   
# For each character in text do your calculation                
for c in text:
    # Generate expression by replacing x  with ascii ordinal number 
    #  prefixed with a multiplicator. 
    # -> character "a" has ordinal number "97"
    # -> expression "3x+2" will be changed to "3*97+2"
    #  likewise the expression "3*x+2" will be changed to "3**97+2" 
    #  which might not be the expected result.
    expr = calc.replace("x", "*" + str(ord(c))) 
    # Evaluate expression
    out = eval_expr(expr)
    # Print cipher with trailing colon and without newline                          
    sys.stdout.write(str(out) + ":")
# Print ending newline
print("")                                           

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM