2012-03-21 60 views
1

我有一個函數在我的views.py在某些行我做了一個id的GET請求。 一旦我得到了id,我想要加密該id,然後再解密。 所以我需要兩個功能基本加密()和解密()函數

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 

我已經看了很多帖子,但沒有找到一個簡單和乾淨的方式我views.py 這裏申請這個我研究

sha1 : You can't decrypt that (implemented for encryption) Mee 2 M2 . AES it deals with 16-digit that multiple of 8 something

我試着也產生6位數的隨機數,但這個想法也不大。 有人可以告訴方式如何做到這一點?在此先感謝

+0

這裏:http://stackoverflow.com/questions/8554286/obfuscating-an-id – georg 2012-03-21 12:57:54

回答

15

使用AES(從pycrypto),但在加密前填充純文本。

這個例子墊空字符的明文(ASCII 0)

from Crypto.Cipher import AES 
import base64 

MASTER_KEY="Some-long-base-key-to-use-as-encyrption-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 

後您解密,剝去空字符:

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.rstrip("\0") 
    return clear_val 
+0

爲什麼填充? – bos 2012-03-21 12:54:36

+0

由於AES算法對16個字節(AES.block_size = 16)的倍數的塊起作用。 – 2012-03-21 13:11:10

+0

完美答案Doug。有沒有一種方法,我們可以避免或建立一些邏輯,我可以使用我的ID,它將來自請求在Django的視圖功能,然後它適合塊大小。我想避免那個主密鑰硬編碼,我們可以讓它變成動態的。我是一名加密新手。但是,謝謝你的幫助。很好的回答!!!!! – 2012-03-22 06:40:00

4

我有完全相同的問題和解決它使用Hashids

這是一些非常好的想法就這麼簡單

hashids = Hashids(salt="this is my salt") 
hashed = hashids.encode(id) # to encode 
id = hashids.decode(hashed) # to decode 
+1

Hashids只是散列整數值,我認爲.. ?? – amulya349 2015-07-16 06:37:30