1

I am trying to store a urandom value into the mySQL Database of my Django project. The value must be totally random for cryptography purposes.

I am trying for hours and I am really frustrated. I googled some answers but the solutions wont work.

If I try this as here suggested Store os.urandom variable to Sqlite database in Django

def createkey():
    random_bytes = urandom(16)
    return b64encode(random_bytes)

key = models.BinaryField(max_length=16, default=createkey)

... i get this error message

django.db.utils.OperationalError: (1067, "Invalid default value for 'key'")

I also tried it with the binascii library os.urandom() decoding Issue like this

def createkey():
    return binascii.hexlify(urandom(16)).decode()

With that above i get this error message:

string argument without an encoding

I am using Python 3.6, Django 1.11.5 and a MySQL Database.

Is there any way to store the value of urandom into a Django Model? I would like to store it in a CharField but I am also glad if it works with other Fields.

stofuser91
  • 43
  • 3

1 Answers1

1

I would attempt to do something like this:

_key = models.BinaryField(blank=True)

Drop the max_length=16 because this does not match up with urandom(16) ... the urandom argument corresponds to the max number of bytes.

Then, within the createkey method called on your Model...you want save a value to the database, and not simply just return a value. The return value is only accessible when called on the Modal instance.... e.g., Modal.createkey().

So, you'll want something more like:

def createkey():
    self._key = binascii.hexlify(urandom(16)).decode()

And call your createkey() method on the view level.

This should resolve your invalid default value for key error.

Without actually replicating what you have, I have a small suspicion that you may even be able to do the following:

def createkey():
    random_bytes = urandom(16)
    return b64encode(random_bytes)

key = models.BinaryField(blank=True, default=self.createkey)

You may even get away with a CharField:

key = models.CharField(max_length = x)

Where x above is BLOCK_SIZE * 2 to hold hex data, or 4 * ( BLOCK_SIZE / 3) for base64 data. BLOCK_SIZE is 16 for your specific example.