Django, python and link encryption

I need to organize some action to generate custom links. Users will click on this link, and in another form, the associated connection with the encrypted string will be decrypted, and the result will be returned.

To do this, I need some encryption function that consumes a number (or string), which is the primary key of my selected item associated with the user account, while also consuming some seed and generating the encryption code that will be decrypted on another page.

so something like this

my_items_pk = 36 #primary key of an item
seed = "rsdjk324j23423j4j2" #some string for crypting
encrypted_string = encrypt(my_items_pk,seed)
#generates some crypted string such as "dsaj2j213jasas452k41k"
and at another page:
decrypt_input = encrypt(decypt,seed)
print decrypt_input
#gives 36

I want my "seed" to be some kind of primary variable (and not some class) for this purpose (i.e. some number or string).

How can I achieve this in python and django?

+5
2

, , Python. , Python Cryptography Toolkit (PyCrypt). , Python . , AES PyCrypt:

from Crypto.Cipher import AES
from urllib import quote

# Note that for AES the key length must be either 16, 24, or 32 bytes
encryption_obj = AES.new('abcdefghijklmnop')
plain = "Testing"

# The plaintext must be a multiple of 16 bytes (for AES), so here we pad it
# with spaces if necessary.
mismatch = len(plain) % 16
if mismatch != 0:
  padding = (16 - mismatch) * ' '
  plain += padding

ciph = encryption_obj.encrypt(plain)

# Finally, to make the encrypted string safe to use in a URL we quote it
quoted_ciph = quote(ciph)

URL-, , GET.

, ; , encryption_obj , , URL-, :

from urllib import unquote

# We've already created encryption_object as shown above

ciph = unquote(quoted_ciph)
plain = encryption_obj.decrypt(ciph)

: ( , ) pk . , , pk . ( , hashlib.)

- , models.py:

class Pk_lookup(models.Model):
  # since we're using sha256, set the max_length of this field to 32
  hashed_pk = models.CharField(primary_key=True, max_length=32)
  key = models.IntegerField()

, - :

import hashlib
import Pk_lookup

hash = hashlib.sha256()
hash.update(str(pk)) # pk has been defined previously
pk_digest = hash.digest()

lookup = Pk_lookup(hashed_pk=pk_digest,key=pk)
lookup.save()

, ; , hexdigest() digest ( ), 64.

+8

Django . . https://docs.djangoproject.com/en/dev/topics/signing/

:

"Django API , API cookie, -.

, :

  • URL- " " , .
  • , , .
  • URL- , , , .
0

All Articles