views:

191

answers:

1

Hello StackOverflow community,

Using Google App Engine, I wrote a keyToSha256() method within a model class (extending db.Model) :

class Car(db.Model):
    def keyToSha256(self):
        keyhash = hashlib.sha256(str(self.key())).digest()
        return keyhash

When displaying the output (ultimately within a Django template), I get garbled text, for example :

�����_ɘ�!`�I�!�;�QeqN��Al�'2

I was expecting something more in line with this :

9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08

Am I missing something important ? Despite reading several guides on ASCII, Unicode, utf-8 and the like, I think I'm still far from mastering the secrets of string encoding/decoding. After browsing StackOverflow and searching for insights via Google, I figured out I should ask the question here. Any idea ? Thanks !

+2  A: 

Use .hexdigest() instead.

Ignacio Vazquez-Abrams
Wonderful, thanks Ignacio ! I just read http://docs.python.org/library/hashlib.html#hashlib.hash.hexdigest : I can't understand why .digest() won't do the trick, though. Strings are so mysterious to me.
Sorw
`.digest()` does give you a string, but it's the raw bytes.
Ignacio Vazquez-Abrams
Great, I understand perfectly ! Python doc was misleading for an inexperienced programmer like me, but reading it one more time with your answer in mind makes it a lot easier to understand. I now get the meaning of "non-binary environments", which I'm pretty sure will be helpful in the future.
Sorw
I'm amazed how many people think the output of hash functions such as SHA1 are hex strings. No offense intended to the OP - it's a common misconception.
Nick Johnson