0

I am pretty new in python, and I have a problem I don't know how to solve.

For example, I have this struct with members such as administrator, berit, etc:

DEFAULT_DATA = {
'administrator': {
    'name': 'Admin',
    'pw': 'secret',
    'is_author': False,
    'is_admin': True
}
'berit': {
     'name': 'berit',
    'pw': 'apa',
    'is_author': False,
    'is_admin': False
 }

This data is then accessible via a method this method:

def DefaultData():
"""Provides default data for Gruyere."""
 return copy.deepcopy(DEFAULT_DATA)

I want to do a md5 hash on the passwords so they are not in plaintext, but I have no idea how to access the fields such as 'pw' and reassign a new value in python.

Here's a guess as to what it might be:

stored_data = data.DefaultData()
for member in stored_data:
   for field in member:
       if field=='pw':
           'pw' = md5.new(salt+pw).hexdigest()    // how do you access the value?
2
  • 4
    Perhaps read a Python tutorial. What you call structs are dictionaries, and they exist to allow simple and efficient access of values by a key (e.g. a string)... Commented Feb 24, 2011 at 17:10
  • 1
    If there was only a way to implement custom types with custom behavior, we wouldn't have to fiddle around with the default types ... Commented Feb 24, 2011 at 17:10

2 Answers 2

1

The values in stored_data are themselves dictionaries. Iterate over the values and apply your algorithm:

stored_data = data.DefaultData()
for data in stored_data.values():
    data['pw'] = md5(salt + data['pw']).hexdigest()

from pprint import pprint
pprint(stored_data)

Output

{'administrator': {'is_admin': True,
                   'is_author': False,
                   'name': 'Admin',
                   'pw': '33e7cb694fb6fb2f848af6774d9ff138'},
 'berit': {'is_admin': False,
           'is_author': False,
           'name': 'berit',
           'pw': '00c10978330d65eb0cb739a629b6ed15'}}
Sign up to request clarification or add additional context in comments.

Comments

1

You access it through the dictionary interface.

stored_data = data.DefaultData()
for member in stored_data.itervalues():
    member['pw'] =  md5.new(salt + member['pw']).hexdigest()

Two comments:

  • First, this doesn't change the value in data, because you're returning a copy of it in DefaultData.
  • Second, as extra security, you might want to include the name field in the hash. At least that way it won't be obvious if two users have the same password.

2 Comments

It is complaining about "String indices must be integer" at the assignment of member['pw']. Why isn't it treated as a dictionary?
for member in stored_data iterates over the keys, which are strings. Iterate over the values.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.