I have a function in my views.py where at some line I make a GET request of an id. Once I get the id, I want to encrypt that id and then later decrypt that also. So I need two functions
def encrypt(id):#let say the id is 100
#do something
return encrypted_id # 6-digit let say 985634
def decrypt(encrypted_id): # Here enter 985634
#do something
return decrypted_id # i should get 100
I have read many posts but not finding an easy and clean way to apply this in my views.py Here what I have studied
sha1 : You can't decrypt that (implemented for encryption) Mee 2 M2 . AES it deals with 16-digit that multiple of 8 something
I tried to generate 6-digit random number also but that idea is also not promising. Can anybody tell a way how to do this ? Thanks in advance
Use AES (from pycrypto), but pad the plain text prior to encrypting it.
This example pads the clear text with null characters (ASCII 0)
from Crypto.Cipher import AES
import base64
MASTER_KEY="Some-long-base-key-to-use-as-encryption-key"
def encrypt_val(clear_text):
enc_secret = AES.new(MASTER_KEY[:32])
tag_string = (str(clear_text) +
(AES.block_size -
len(str(clear_text)) % AES.block_size) * "\0")
cipher_text = base64.b64encode(enc_secret.encrypt(tag_string))
return cipher_text
After you decrypt, strip the null characters:
def decrypt_val(cipher_text):
dec_secret = AES.new(MASTER_KEY[:32])
raw_decrypted = dec_secret.decrypt(base64.b64decode(cipher_text))
clear_val = raw_decrypted.decode().rstrip("\0")
return clear_val
I had exactly the same problem and solved it by using Hashids.
It is as simple as
hashids = Hashids(salt="this is my salt")
hashed = hashids.encode(id) # to encode
id = hashids.decode(hashed) # to decode
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With