how to encrypt and decrypt pk from django url without using any package basically i have a url like
example.com/update/1
where pk=1
i want to encrypt the pk like pk 1 = 345345435cgsfd2asdfaas
There is no inbuld method, to do this I think, but using TimestampSigner, you can do the following:
Using TimestampSigner, you can encrypt your PK, and later decrypt when you want the original string.
>>> from datetime import timedelta
>>> from django.core.signing import TimestampSigner
>>> signer = TimestampSigner()
>>> value = signer.sign(str(pk)) # encrypt the PK.
>>> value
'1:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
>>> value = value.replace(pk,"") # doing this because, it append the original primary key + encrypted string.
>>> value # use this PK to show in the URL.
'1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
>>> repack = "{}:{}".format(pk,value) # When you want back the original PK, add the PK + encrypted string.
>>>repack
'1:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
>>> signer.unsign(repack) # decrypt the PK.
'1'
Hope this will be helpfull for you.
If you don't want to expose pk to the url then you can use signing.dumps while encrypting and signing.loads on decryption. Serialized object is signed using TimestampSigner.
>>> from django.core import signing
>>> value = signing.dumps({"pk": "25"})
>>> value
'eyJwayI6IjI1In0:1g9Q4d:RJRYtpklLqaa3ey9c4d4sI0DKMc'
>>> signing.loads(value)
{'pk': '25'}
>>> signing.loads(value,max_age=10)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/avinash/.virtualenvs/mapd/lib/python3.6/site-packages/django/core/signing.py", line 140, in loads
base64d = force_bytes(TimestampSigner(key, salt=salt).unsign(s, max_age=max_age))
File "/home/avinash/.virtualenvs/mapd/lib/python3.6/site-packages/django/core/signing.py", line 209, in unsign
'Signature age %s > %s seconds' % (age, max_age))
django.core.signing.SignatureExpired: Signature age 25.847949981689453 > 10 seconds
>>>
$(function() {
// Replace each URL
$(".exampleclass").each(function(index) {
// Get current URL
var url = $(this).attr('href');
// Encode URL
var encodedUrl = encodeURIComponent(url);
// Replace
$(this).attr("href", encodedUrl);
});
});
This is the original URL:
http://10.91.161.54:8181/validate_/listActivi/314/
This is the URL with replacement:
http://10.91.161.54:8181/validate_/%2Fvalidate_%2FlistActivi%2F314%2F%20