I have to sign a value, in my case emails, and I have to store the signed value in a Django CharField. I am using the Signer.sign method of the django.core.signing module. Since I would like to insert also the max_length parameter for the db field, my question is, what would be the minimal value I can put in the max_length in order to always successfully store it in the db.
Asked
Active
Viewed 1,081 times
2 Answers
1
In fact the signing token length grows with the input value:
>>> from django.core.signing import Signer
>>> signer = Signer()
>>> signer.sign('a')
'a:JRYbTbX2xBKZAgJxbzUzsl80vIQ'
>>> signer.sign('ab')
'ab:ThbCyQ9bQpAX4vMAmYSEtbtF7Y4'
>>> signer.sign('abc')
'abc:4_rTdYDe18bPklTTKYIsJaB9_oM'
>>> signer.sign('abcd')
'abcd:RzGFLsNgRv-LQ4lEorvNPjGH5LM'
>>> signer.sign('abcde')
'abcde:oOdfJjZ14Jz2F4aHD3pQMBC9fAA'
>>> signer.sign('abcdefghijkl')
'abcdefghijkl:Wz1gPy4QS7ZoCyXuKgUFG-ofxpU'
However, according to my testing, the maximum size of the token is 27. According to this answer What is the maximum length of a valid email address? maximum length of an email address is 254 characters. max_length attribute of your TextField should be 282 (254+27+1 for separator).
illagrenan
- 6,033
- 2
- 54
- 66
-
1The signature uses HMAC with SHA-1 as its hash function, and then encodes the output in base64, stripping away any padding character `=` from the base64 output. The output of SHA-1 is 20 bytes, and base64 increases the length by 33%, so the maximum of 27 bytes that you found in your tests is correct. – knbk Apr 23 '17 at 20:38
0
this is what they have given on the Django docs.
from django.core.signing import Signer
>>> signer = Signer()
>>> value = signer.sign('My string')
>>> value
'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
the sign string is of length of 28 (including ':') plus the length of your email string.to be on the safe side I would suggest you to use Django TextField instead of CharField
badiya
- 2,247
- 13
- 23
-
1There is no limit on `max_length`. The only limit is that a MySQL index has a maximum length of 767 bytes, which means that if you're using an index or unique constraint on a `CharField` with a character set that uses 3 bytes per character, _then_ the limit is 255. When using a different database or no index, there is no limit on the maximum length (but there may be other limits, e.g. on the size of a row). – knbk Apr 23 '17 at 20:22