0

In my django settings.py file there is:

SECRET_KEY = '1qpps_5yf@e_++wwicusr*8#lm)^m=rjhgk#&qq1w*p*2d3c4z'

I need some function to convert this string (well it can be any string, lets assume it's not empty) to shorter/longer string. I mean I need key but for example with length=16. Well If SECRET_KEY is longer than 16 it's easy to just substring it, but if its shorter then I don't want to "pad" missing values with some constatnt char.

So I need function which takes string with length > 0 and generates key with length = 16. Even more simply: I need key generator which will generate 16 characters string based on some seed (seed = SECRET_KEY)

edit --------------------

found good solution here: Efficiently generate a 16-character, alphanumeric string

import random
random.seed(settings.SECRET_KEY)
key = ''.join(random.choice('1234567890qwertyuiopasdfghjklzxcvbnm,./;@[]!#$%^&*()_+=-') for i in range(16))

I hope random.seed(settings.SECRET_KEY) is not big security whole in django app :P

Community
  • 1
  • 1
user606521
  • 14,486
  • 30
  • 113
  • 204

1 Answers1

2

You can hash any value, and get 16 bytes from it:

>>> import hashlib
>>> hashlib.md5("123").digest()
' ,\xb9b\xacY\x07[\x96K\x07\x15-#Kp'

You haven't said what characters are acceptable in your strings, this will give you arbitrary byte values.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662