3

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?

1
  • 1
    Could you provide a link for that quote? If it's encrypted in publicly-available code, then the code to decrypt it will also be available and it doesn't really help!
    – jonrsharpe
    Mar 17, 2015 at 14:04

2 Answers 2

4

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 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
3
  • Interesting, that's a good idea! What if I wanted to commit the external file? (Essentially, I want to be able to put the project on GitHub) Mar 17, 2015 at 14:24
  • 1
    If you commit the external file your key will almost certainly be stolen and used. There are bots on GitHub specifically tailored to stealing keys in public code. Your best bet (if you want to keep your key secure) is to shuffle the external file along with your program wherever you want to run it.
    – cziemba
    Mar 17, 2015 at 14:27
  • 3
    @user97912 the important point that both cziemba and jonrsharpe are implicitly making is that you can't put the (functional) project on github without revealing the key - it's technically impossible. Using this answer, though, you minimize the part you don't publish Mar 17, 2015 at 14:34
1

Saving keys in another file as @cziemba pointed out is a common method. However, make sure to include the file in .gitignore if you'll be using git, so you don't commit the keys and probably push it to github. You could also save the key outside of the repo and use absolute path to read it e.g ~/Documents/my_secrets/twitter.json.

Another common method is to add keys or tokens to the environment variable. This article shows how to set environment variables.

To get the environment variable e.g "TWITTER_SECRET" in your code, use

import os
secret = os.environ["TWITTER_SECRET"]

os.environ is a dictionary of environment variables and would raise IndexError if "TWITTER_SECRET" is not in the environment variable. So you might want to use dictionary get method or try except statement depending on the need of your program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.