Reputation: 435
Instead of keeping keys in my application I intent to read the keys from local file system into a variable (array of strings) and use those array elements in my oAuth APIs. However, when i used keys (in plaintext) as argument to OAuth APIs, authentication succeeds. BUT authentication failed when same value in read into a variable from file & that variable is passed to OAuth API. Tried comparing the key value and variable value t find out they don't match though they same exactly same.
Input file looks as below:
$cat .keys
k1='jFOMZ0bI60fDAEKw53lYCj2r4'
k2='LNkyPehneIi8HeqTg1ji74H42jFkkBxZolRfzNFmaJKwLg7R7E'
secret_keys=[]
def keys_io():
key_file = open('/Users/homie/.keys', 'r+')
for key in range(1,5):
secret_keys.append(key_file.readline().split("=")[1])
print secret_keys[0]
print (secret_keys[0] == "jFOMZ0bI60fDAEKw53lYCj2r4")
keys_io()
Output:
jFOMZ0bI60fDAEKw53lYCj2r4
False
What am i missing here?
Upvotes: 0
Views: 427
Reputation: 291
When you read a text file from Python, you need to escape the new line character first. Another problem is you have single quote in between the input text. So you need to make change to:
secret_keys.append(key_file.readline().strip().split("=")[1])
and
if(secret_keys[0] == "\'jFOMZ0bI60fDAEKw53lYCj2r4\'"):
Upvotes: 0
Reputation: 81594
You should strip
the key that you read from the file, as it has a trailing \n
:
print(secret_keys[0].strip() == "jFOMZ0bI60fDAEKw53lYCj2r4")
Or do it when reading it:
for key in range(1,5):
secret_keys.append(key_file.readline().split("=")[1].strip())
Upvotes: 1
Reputation: 160377
If leading-trailing characters are bugging you, remove them with slicing, i.e [1:-1]
to remove first-last quotations.
I also refactored your function a bit:
def keys_io():
with open('.keys', 'r+') as f:
for line in f:
secret_keys.append(line.split('=')[1].strip()[1:-1])
print secret_keys[0]
print (secret_keys[0] == "jFOMZ0bI60fDAEKw53lYCj2r4"
for line in <opened_file>
instead of other methods if you need to examine all lines.strip()
without arguments to remove unwanted space.After these changes, the keys_io
file works like a charm for me when using the .key
file you presented.
Upvotes: 1