I am trying to store some cryptographic data in couchdb. I need to store a salt and encrypted password in couchdb. The salt is generated using python's os.urandom(8) and the sample output of that would look like:

'z/\xfe\xdf\xdeJ=y'

I'm using python-couchdb api to store the document. When I try to save the document I get:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "build/bdist.macosx-10.7-intel/egg/couchdb/client.py", line 343, in __setitem__
    status, headers, data = resource.put_json(body=content)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/http.py", line 499, in put_json
    **params)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/http.py", line 514, in _request_json
    headers=headers, **params)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/http.py", line 510, in _request
    credentials=self.credentials)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/http.py", line 260, in request
    body = json.encode(body).encode('utf-8')
  File "build/bdist.macosx-10.7-intel/egg/couchdb/json.py", line 68, in encode
    return _encode(obj)
  File "build/bdist.macosx-10.7-intel/egg/couchdb/json.py", line 129, in <lambda>
    dumps(obj, allow_nan=False, ensure_ascii=False)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 204, in encode
    return ''.join(chunks)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfe in position 3: ordinal not in range(128)
有帮助吗?

解决方案

Encode it as either base64 or as hex before saving, or save it in a binary field.

其他提示

Encode the output of urandom in base 64 like this:

os.urandom(8).encode('base64')

As per the example in this thread

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top