Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic encrypt() and decrypt() function

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

like image 622
the_game Avatar asked Mar 21 '12 11:03

the_game


2 Answers

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
like image 96
Doug Harris Avatar answered Sep 20 '22 13:09

Doug Harris


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
like image 28
Andy Avatar answered Sep 21 '22 13:09

Andy