0
私はユーザーにPOSTデータを許可し、RSA公開鍵暗号化とbase64でエンコードされた文字列を返す単純なフラスコアプリケーションを構築しています。FlaskでのRSA暗号化UnicodeDecodeError
フラスコアプリケーションルートは暗号化機能は、以下の
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
次のようになり、すべてのコマンドラインからうまく機能し、次の
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
のように見えます。しかし、フラスコ内呼び出されたときに、私は次のようUnicodeDecodeError
UnicodeDecodeError: 'ascii' codec can't decode byte 0xda in position 0: ordinal not in range(128)
を取得し、私は、UTF-8への切り替えをしようとしたと同様のエラー
編集を取得しました: 私のpythonでアクティブ2.7 virtualenvのをテストしています。出力そのものも問題ではないようです。仲介ステップを実行しても、これは同じ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)
おそらくあなたのコンソールにFlask、2.xのPython - 3.xの異なるバージョンを使用しています - 後者の 'base64.b64encode'はバイトではなく文字列を生成するので、デコードする必要はありません何でも安全な側にするには、常にbase64出力をデコードします。 'return output.decode(" latin-1 ")' – zwer