2015-05-04 99 views
-1

我一直在試圖在python中生成一個臨時url,這個url會將一些數據,我需要確保不會改變,所以我會在最後添加一個哈希,但我保留無論我嘗試什麼,都以bString結尾,任何人都可以指出我做錯了什麼? 這裏是我的代碼 哦樣品,我知道,也許改變算法/編碼可能會解決這個問題,但我不能找到一個合適的,可以在任何downvoter解釋他爲什麼downvoted在Python中生成一個臨時URL

import hashlib 
import datetime 
from Crypto.Cipher import AES 

def checkTemp(tempLink): 
    encrypter = AES.new('123456789', AES.MODE_CBC, 'this is an iv456') 
    decryption = encrypter.decrypt(tempLink) 
    length = len(decryption) 

    hash_code = decryption[length-32:length] 
    data= decryption[:length-32].strip() 
    hasher = hashlib.sha256() 
    hasher.update(data) 
    hashCode = hasher.digest() 

    if(hash_code==hashCode): 
     array = data.decode().split(",",5) 
     print("expiry date is :"+ str(array[5])) 
     return array[0],array[1],array[2],array[3],array[4] 
    else: 
     return "","","","","" 

def createTemp(inviter,email,role,pj_name,cmp_name): 
    delim = ',' 
    data = inviter+delim+email+delim+role+delim+pj_name+delim+cmp_name+delim+str(datetime.datetime.now().time()) 
    data = data.encode(encoding='utf_8', errors='strict') 

    hasher = hashlib.sha256() 
    hasher.update(data) 

    hashCode = hasher.digest() 
    encrypter = AES.new('123456789', AES.MODE_CBC, 'this is an iv456') 
    # to make the link a multiple of 16 by adding for AES with the addition of spaces 
    newData = data+b' '*(len(data)%16) 
    result = encrypter.encrypt(newData+hashCode) 

    return result 
#print(str(link).split(",",5)) 
link = createTemp("name","[email protected]","Designer","Project Name","My Company") 
print(link) 
inviter,email,role,project,company = checkTemp(link) 
+0

我沒有downvote使用前unhexify它,但你的問題讀起來就像意識的某人流。添加一些標點符號,句子停止和大寫字母,以幫助讀者解析上面寫的內容。 – Hooked

+0

@Hooked謝謝,以及我有點新,所以我不擅長張貼我的想法,再加上我高興沮喪,失去了嘗試修復它,讓我更加困惑。 反正感謝指針 – Newbie

回答

0

的問題是不能夠產出影響正常的字符串,因爲加密將導致幾乎是不可能的字符進行編碼,因此該解決方案是使用binascii來編碼bStrings我們和解碼他們

import binascii 

那麼我們編碼產生鏈接可用字符串

hexedLink = binascii.hexlify(link).decode() 

,我們在方法

inviter,email,role,project,company = checkTemp(binascii.unhexlify(hexedLink))