如何在不使用任何包的情况下从django url加密和解密pk 基本上我有一个像
的网址example.com/update/1
其中pk = 1
我想加密pk,如pk 1 = 345345435cgsfd2asdfaas
答案 0 :(得分:4)
我认为没有inbuld方法可以执行此操作,但使用TimestampSigner,您可以执行以下操作:
使用TimestampSigner,您可以加密PK,然后在需要原始字符串时解密。
>>> 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'
希望这对你有所帮助。
答案 1 :(得分:0)
如果您不想向网址公开pk
,则可以在加密时使用signing.dumps
,在解密时可以使用signing.loads
。序列化的对象使用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
>>>
答案 2 :(得分:0)
$(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);
});
});
这是原始网址:
http://10.91.161.54:8181/validate_/listActivi/314/
这是替换后的网址:
http://10.91.161.54:8181/validate_/%2Fvalidate_%2FlistActivi%2F314%2F%20