簡體   English   中英

基本的crypto()和Delete()函數

[英]Basic encrypt() and decrypt() function

我的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:您無法解密(為加密實現)Mee 2 M2。 AES處理8位數字的16位數字

我也嘗試生成6位數的隨機數,但是這個想法也沒有希望。 有人可以告訴一個方法怎么做嗎? 提前致謝

使用AES(來自pycrypto ),但是在加密之前填充純文本。

本示例使用空字符(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

解密后,刪除空字符:

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

我遇到了完全相同的問題,並通過使用Hashids解決了它。

就這么簡單

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM