通过Flask UnicodeDecodeError进行RSA加密

时间:2017-06-08 23:06:51

标签: python encryption flask

我正构建一个简单的烧瓶应用程序,允许用户POST数据,我们返回RSA公钥加密和base64编码的字符串。

Flask App Route如下所示

def index(eyaml_output=""):
if request.method == 'GET':
    return render_template('index.html.j2', eyaml_output=eyaml_output)
elif request.method == 'POST':
    input = request.form['eyaml_input']
    output = helpers.encrypt(input)
    eyaml_output = output

加密功能如下所示

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import base64

def encrypt(arg):
    with open('eyaml_public.key') as public_key_file:
        public_key = public_key_file.read()

    pubkey = RSA.importKey(public_key)
    cipher = PKCS1_OAEP.new(pubkey)

    output = base64.b64encode(cipher.encrypt(arg))

    return output

这一切从命令行运行良好。但是当在烧瓶中调用时,我得到以下UnicodeDecodeError

UnicodeDecodeError: 'ascii' codec can't decode byte 0xda in position 0: ordinal not in range(128)

我尝试过切换到utf-8并收到类似的错误

编辑: 我正在测试python 2.7 virtualenv active。输出本身似乎也不重要。即使在执行中间步骤时,也会出现相同的Unicode错误。问题出现在加密部分,而不是base64编码。

下方的完整堆栈跟踪
Traceback (most recent call last):
  File "/Users/bchen/Git/Stoneridge/ansible/eyaml-ansible-
filter/flask/.venv/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/bchen/Git/Stoneridge/ansible/eyaml-ansible-
filter/flask/.venv/lib/python2.7/site-packages/flask/app.py", line 
1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/bchen/Git/Stoneridge/ansible/eyaml-ansible-
filter/flask/.venv/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/bchen/Git/Stoneridge/ansible/eyaml-ansible-
filter/flask/.venv/lib/python2.7/site-packages/flask/app.py", line 
1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/bchen/Git/Stoneridge/ansible/eyaml-ansible-
filter/flask/.venv/lib/python2.7/site-packages/flask/app.py", line 
1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "app.py", line 13, in index
    output = helpers.encrypt(input)
  File "/Users/bchen/Git/Stoneridge/ansible/eyaml-ansible-
filter/flask/helpers.py", line 12, in encrypt
    fake_output = base64.b64encode(cipher.encrypt(arg))
  File "/Users/bchen/Git/Stoneridge/ansible/eyaml-ansible-
filter/flask/.venv/lib/python2.7/site-
packages/Crypto/Cipher/PKCS1_OAEP.py", line 150, in encrypt
    db = lHash + ps + bchr(0x01) + message
UnicodeDecodeError: 'ascii' codec can't decode byte 0xda in position 0: 
ordinal not in range(128)

1 个答案:

答案 0 :(得分:2)

如果您在arg参数上添加对.encode()的调用,则该调用应该有效。 encrypt方法需要一个字节序列,但获得str