Skip to content

Instantly share code, notes, and snippets.

@parhammmm
Forked from treyhunner/models.py
Created December 8, 2012 19:20

Revisions

  1. parhammmm revised this gist Dec 10, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion models.py
    Original file line number Diff line number Diff line change
    @@ -54,7 +54,7 @@ def __init__(self, *args, **kwargs):
    )

    def _encrypted_pk(self):
    encryption_obj = DES.new(self.model.PK_SECRET_KEY) # This 8 character secret key should be changed!
    encryption_obj = DES.new(self.PK_SECRET_KEY) # This 8 character secret key should be changed!
    return base36encode(struct.unpack('<Q', encryption_obj.encrypt(
    str(struct.pack('<Q', self.pk))
    ))[0])
  2. parhammmm revised this gist Dec 10, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion models.py
    Original file line number Diff line number Diff line change
    @@ -54,7 +54,7 @@ def __init__(self, *args, **kwargs):
    )

    def _encrypted_pk(self):
    encryption_obj = DES.new(self.PK_SECRET_KEY) # This 8 character secret key should be changed!
    encryption_obj = DES.new(self.model.PK_SECRET_KEY) # This 8 character secret key should be changed!
    return base36encode(struct.unpack('<Q', encryption_obj.encrypt(
    str(struct.pack('<Q', self.pk))
    ))[0])
  3. parhammmm revised this gist Dec 8, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion models.py
    Original file line number Diff line number Diff line change
    @@ -70,7 +70,7 @@ class ExampleModelManager(EncryptedPKModelManager):


    class ExampleModel(EncryptedPKModel):
    PK_ENCRYPTION_KEY = '8charkey'
    PK_SECRET_KEY = '8charkey'
    objects = ExampleModelManager()
    example_field = models.CharField(max_length=32)

  4. parhammmm revised this gist Dec 8, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion models.py
    Original file line number Diff line number Diff line change
    @@ -27,7 +27,7 @@ def base36decode(numstr):
    return int(numstr,36)


    class EncryptedPKManager(models.Manager):
    class EncryptedPKModelManager(models.Manager):
    """This manager allows models to be identified based on their encrypted_pk value."""

    def get(self, *args, **kwargs):
  5. parhammmm revised this gist Dec 8, 2012. 1 changed file with 11 additions and 8 deletions.
    19 changes: 11 additions & 8 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -6,7 +6,6 @@
    from Crypto.Cipher import DES
    from django.db import models


    def base36encode(number):
    """Encode number to string of alphanumeric characters (0 to z). (Code taken from Wikipedia)."""
    if not isinstance(number, (int, long)):
    @@ -28,32 +27,35 @@ def base36decode(numstr):
    return int(numstr,36)


    class EncryptedPKModelManager(models.Manager):
    class EncryptedPKManager(models.Manager):
    """This manager allows models to be identified based on their encrypted_pk value."""

    def get(self, *args, **kwargs):
    encrypted_pk = kwargs.pop('encrypted_pk', None)
    if encrypted_pk:
    # If found, decrypt encrypted_pk argument and set pk argument to the appropriate value
    kwargs['pk'] = struct.unpack('<Q', self.model.encryption_obj.decrypt(
    encryption_obj = DES.new(self.model.PK_SECRET_KEY) # This 8 character secret key should be changed!
    kwargs['pk'] = struct.unpack('<Q', encryption_obj.decrypt(
    struct.pack('<Q', base36decode(encrypted_pk))
    ))[0]
    return super(EncryptedPKModelManager, self).get(*args, **kwargs)

    return super(EncryptedPKManager, self).get(*args, **kwargs)


    class EncryptedPKModel(models.Model):
    """Adds encrypted_pk property to children which returns the encrypted value of the primary key."""
    encryption_obj = DES.new('8charkey') # This 8 character secret key should be changed!

    def __init__(self, *args, **kwargs):
    super(EncryptedPKModel, self).__init__(*args, **kwargs)
    setattr(
    self.__class__,
    "encrypted_%s" % (self._meta.pk.name,),
    property(self.__class__._encrypted_pk)
    )
    )

    def _encrypted_pk(self):
    return base36encode(struct.unpack('<Q', self.encryption_obj.encrypt(
    encryption_obj = DES.new(self.PK_SECRET_KEY) # This 8 character secret key should be changed!
    return base36encode(struct.unpack('<Q', encryption_obj.encrypt(
    str(struct.pack('<Q', self.pk))
    ))[0])

    @@ -68,11 +70,12 @@ class ExampleModelManager(EncryptedPKModelManager):


    class ExampleModel(EncryptedPKModel):
    PK_ENCRYPTION_KEY = '8charkey'
    objects = ExampleModelManager()
    example_field = models.CharField(max_length=32)


    # Example usage:
    # example_instance = ExampleModel.objects.get(pk=1)
    # url_pk = example_instance.encrypted_pk
    # ExampleModel.objects.get(encrypted_pk=url_pk)
    # ExampleModel.objects.get(encrypted_pk=url_pk)
  6. @treyhunner treyhunner revised this gist Apr 4, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion models.py
    Original file line number Diff line number Diff line change
    @@ -8,7 +8,7 @@


    def base36encode(number):
    """Encode number to string of characters in the range 0 9 and a to z. (Code taken from Wikipedia)."""
    """Encode number to string of alphanumeric characters (0 to z). (Code taken from Wikipedia)."""
    if not isinstance(number, (int, long)):
    raise TypeError('number must be an integer')
    if number < 0:
  7. @treyhunner treyhunner revised this gist Apr 4, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion models.py
    Original file line number Diff line number Diff line change
    @@ -33,7 +33,7 @@ class EncryptedPKModelManager(models.Manager):
    def get(self, *args, **kwargs):
    encrypted_pk = kwargs.pop('encrypted_pk', None)
    if encrypted_pk:
    # If found, decrypt encrypted_pk keyword argument and set pk argument to the appropriate value
    # If found, decrypt encrypted_pk argument and set pk argument to the appropriate value
    kwargs['pk'] = struct.unpack('<Q', self.model.encryption_obj.decrypt(
    struct.pack('<Q', base36decode(encrypted_pk))
    ))[0]
  8. @treyhunner treyhunner revised this gist Dec 17, 2010. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    # This code is under the MIT license.
    # Inspired by this StackOverflow question:
    http://stackoverflow.com/questions/3295405/creating-django-objects-with-a-random-primary-key

  9. @treyhunner treyhunner revised this gist Dec 11, 2010. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion models.py
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,5 @@
    # Inspired by this StackOverflow question: http://stackoverflow.com/questions/3295405/creating-django-objects-with-a-random-primary-key
    # Inspired by this StackOverflow question:
    http://stackoverflow.com/questions/3295405/creating-django-objects-with-a-random-primary-key

    import struct
    from Crypto.Cipher import DES
  10. @treyhunner treyhunner revised this gist Dec 11, 2010. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    # Inspired by this StackOverflow question: http://stackoverflow.com/questions/3295405/creating-django-objects-with-a-random-primary-key

    import struct
    from Crypto.Cipher import DES
    from django.db import models
  11. @treyhunner treyhunner revised this gist Dec 11, 2010. 1 changed file with 13 additions and 5 deletions.
    18 changes: 13 additions & 5 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -29,21 +29,29 @@ class EncryptedPKModelManager(models.Manager):
    def get(self, *args, **kwargs):
    encrypted_pk = kwargs.pop('encrypted_pk', None)
    if encrypted_pk:
    # If the encrypted_pk keyword argument was found, decrypt it and set the pk argument to the appropriate value
    kwargs['pk'] = struct.unpack('<Q', self.model.encryption_obj.decrypt(struct.pack('<Q', base36decode(encrypted_pk))))[0]
    # If found, decrypt encrypted_pk keyword argument and set pk argument to the appropriate value
    kwargs['pk'] = struct.unpack('<Q', self.model.encryption_obj.decrypt(
    struct.pack('<Q', base36decode(encrypted_pk))
    ))[0]
    return super(EncryptedPKModelManager, self).get(*args, **kwargs)


    class EncryptedPKModel(models.Model):
    """Models that inherit from this class will have an encrypted_pk property that returns the encrypted value of the primary key."""
    """Adds encrypted_pk property to children which returns the encrypted value of the primary key."""
    encryption_obj = DES.new('8charkey') # This 8 character secret key should be changed!

    def __init__(self, *args, **kwargs):
    super(EncryptedPKModel, self).__init__(*args, **kwargs)
    setattr(self.__class__, "encrypted_%s" % (self._meta.pk.name,), property(self.__class__._encrypted_pk))
    setattr(
    self.__class__,
    "encrypted_%s" % (self._meta.pk.name,),
    property(self.__class__._encrypted_pk)
    )

    def _encrypted_pk(self):
    return base36encode(struct.unpack('<Q', self.encryption_obj.encrypt(str(struct.pack('<Q', self.pk))))[0])
    return base36encode(struct.unpack('<Q', self.encryption_obj.encrypt(
    str(struct.pack('<Q', self.pk))
    ))[0])

    encrypted_pk = property(_encrypted_pk)

  12. @treyhunner treyhunner revised this gist Dec 11, 2010. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    # Inspired by this StackOverflow question: http://stackoverflow.com/questions/3295405/creating-django-objects-with-a-random-primary-key

    import struct
    from Crypto.Cipher import DES
    from django.db import models
  13. @treyhunner treyhunner revised this gist Dec 11, 2010. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -37,6 +37,11 @@ def get(self, *args, **kwargs):
    class EncryptedPKModel(models.Model):
    """Models that inherit from this class will have an encrypted_pk property that returns the encrypted value of the primary key."""
    encryption_obj = DES.new('8charkey') # This 8 character secret key should be changed!

    def __init__(self, *args, **kwargs):
    super(EncryptedPKModel, self).__init__(*args, **kwargs)
    setattr(self.__class__, "encrypted_%s" % (self._meta.pk.name,), property(self.__class__._encrypted_pk))

    def _encrypted_pk(self):
    return base36encode(struct.unpack('<Q', self.encryption_obj.encrypt(str(struct.pack('<Q', self.pk))))[0])

  14. @treyhunner treyhunner revised this gist Dec 11, 2010. 1 changed file with 5 additions and 2 deletions.
    7 changes: 5 additions & 2 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -34,20 +34,23 @@ def get(self, *args, **kwargs):
    return super(EncryptedPKModelManager, self).get(*args, **kwargs)


    class EncryptedPKModel:
    class EncryptedPKModel(models.Model):
    """Models that inherit from this class will have an encrypted_pk property that returns the encrypted value of the primary key."""
    encryption_obj = DES.new('8charkey') # This 8 character secret key should be changed!
    def _encrypted_pk(self):
    return base36encode(struct.unpack('<Q', self.encryption_obj.encrypt(str(struct.pack('<Q', self.pk))))[0])

    encrypted_pk = property(_encrypted_pk)

    class Meta:
    abstract = True


    class ExampleModelManager(EncryptedPKModelManager):
    pass


    class ExampleModel(models.Model,EncryptedPKModel):
    class ExampleModel(EncryptedPKModel):
    objects = ExampleModelManager()
    example_field = models.CharField(max_length=32)

  15. @treyhunner treyhunner created this gist Dec 10, 2010.
    58 changes: 58 additions & 0 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    import struct
    from Crypto.Cipher import DES
    from django.db import models


    def base36encode(number):
    """Encode number to string of characters in the range 0 9 and a to z. (Code taken from Wikipedia)."""
    if not isinstance(number, (int, long)):
    raise TypeError('number must be an integer')
    if number < 0:
    raise ValueError('number must be positive')

    alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'
    base36 = ''
    while number:
    number, i = divmod(number, 36)
    base36 = alphabet[i] + base36

    return base36 or alphabet[0]


    def base36decode(numstr):
    """Convert a base-36 string (made of alphanumeric characters) to its numeric value."""
    return int(numstr,36)


    class EncryptedPKModelManager(models.Manager):
    """This manager allows models to be identified based on their encrypted_pk value."""
    def get(self, *args, **kwargs):
    encrypted_pk = kwargs.pop('encrypted_pk', None)
    if encrypted_pk:
    # If the encrypted_pk keyword argument was found, decrypt it and set the pk argument to the appropriate value
    kwargs['pk'] = struct.unpack('<Q', self.model.encryption_obj.decrypt(struct.pack('<Q', base36decode(encrypted_pk))))[0]
    return super(EncryptedPKModelManager, self).get(*args, **kwargs)


    class EncryptedPKModel:
    """Models that inherit from this class will have an encrypted_pk property that returns the encrypted value of the primary key."""
    encryption_obj = DES.new('8charkey') # This 8 character secret key should be changed!
    def _encrypted_pk(self):
    return base36encode(struct.unpack('<Q', self.encryption_obj.encrypt(str(struct.pack('<Q', self.pk))))[0])

    encrypted_pk = property(_encrypted_pk)


    class ExampleModelManager(EncryptedPKModelManager):
    pass


    class ExampleModel(models.Model,EncryptedPKModel):
    objects = ExampleModelManager()
    example_field = models.CharField(max_length=32)


    # Example usage:
    # example_instance = ExampleModel.objects.get(pk=1)
    # url_pk = example_instance.encrypted_pk
    # ExampleModel.objects.get(encrypted_pk=url_pk)