How should I encrypt API tokens in Python?
Question: I've written a basic Python application that uses Twitter's API. I need to be
able to encode my API secret as it should never be human-readable within my
program (Twitter's words). How should I do this in Python? Is it possible?


Answer: Store the API Key in an external file and load it at runtime. Just be sure to
never commit the external file or publish it. Obfuscating the key once loaded
doesn't really prevent them from stealing it (especially if they have the
source to unwind your obfuscation as
[jonrsharpe](http://stackoverflow.com/questions/29100900/how-should-i-encrypt-
api-tokens-in-python/29101478#comment46432400_29100900) pointed out).

Heres a crude example, I'm sure you could refine it to suit your needs:

secret_keys file:

    
    
    {
        "TWITTER_SECRET" : "somebase64encodedkey"
    }
    

python:

    
    
    import json
    
    secrets_filename = 'secret_keys'
    api_keys = {}
    with open(secrets_filename, 'r') as f:
        api_keys = json.loads(f.read())
    
    print api_keys['TWITTER_SECRET'] # somebase64encodedkey
    

