2017-11-06 12 views
0

vuforia의 API에서 내 대상을 가져 오려고하지만 인코딩 된 데이터 인 "Authorization"헤더의 마지막 값을 전달할 수 없습니다. 나는이되는군요 : 나는 여전히 vuforia's documentation하지만 다음있어해시링하기 전에 유니 코드 개체를 인코딩해야합니다. vuforia

유니 코드 객체가이 코드의 시도 조각에

해싱 전에 인코딩해야합니다, 뭔가 내 코드와 나는 돈에 문제가 있습니다 무엇인지 알 수 없습니다.

import base64 
import hashlib 
import hmac 

import requests 
from flask import Flask, request 
from email.utils import formatdate 
import logging 

app = Flask(__name__) 


@app.route('/') 
def hello_world(): 
    try: 
     import http.client as http_client 
    except ImportError: 
     # Python 2 
     import httplib as http_client 
    http_client.HTTPConnection.debuglevel = 1 

    logging.basicConfig() 
    logging.getLogger().setLevel(logging.DEBUG) 
    requests_log = logging.getLogger("requests.packages.urllib3") 
    requests_log.setLevel(logging.DEBUG) 
    requests_log.propagate = True 

    url = 'https://vws.vuforia.com/targets' 
    req = requests.Request('GET', url) 
    req.headers = setHeaders(req) 
    resp = requests.Session().send(req.prepare()) 

    return resp.text 


def compute_md5_hex(data): 
    """Return the hex MD5 of the data""" 
    h = hashlib.md5() 
    h.update(data) 
    return h.hexdigest() 


def compute_hmac_base64(key, data): 
    """Return the Base64 encoded HMAC-SHA1 using the provide key""" 
    h = hmac.new(key, None, hashlib.sha1) 
    h.update(data) 
    return base64.b64encode(h.digest()) 


def setHeaders(request): 
    date = formatdate(None, localtime=False, usegmt=True) 
    accessKey = "ce1500fhfth429279173fd839f9d414532014a3da" 
    secret_key = b"5d3fdawd7211447c35be607ae5a08ec794a09d71d" 
    headers = {'Date': date, 'Authorization': "VWS " + accessKey + ":" + tmsSignature(request, secret_key)} 

    return headers 


def tmsSignature(request, secretKey): 
    method = request.method 
    contentType = "" 
    hexDigest = "d41d8cd98f00b204e9800998ecf8427e" 
    if method == "GET" or method == "POST": 
     pass 
     # Do nothing because the strings are already set correctly 
    elif method == "POST" or method == "PUT": 
     contentType = "application/json" 
     # If this is a POST or PUT the request should have a request body 
     hexDigest = compute_md5_hex(request) 
    else: 
     print("ERROR: Invalid content type passed to Sig Builder") 

    # Date in the header and date used to calculate the hash must be the same 
    dateValue = formatdate(None, localtime=False, usegmt=True) 
    requestPath = str(request.url) 
    components_to_sign = list() 
    components_to_sign.append(method) 
    components_to_sign.append(str(hexDigest)) 
    components_to_sign.append(str(contentType)) 
    components_to_sign.append(str(dateValue)) 
    components_to_sign.append(str(requestPath)) 
    string_to_sign = "\n".join(components_to_sign) 
    shaHashed = "" 
    try: 
     shaHashed = compute_hmac_base64(secretKey, string_to_sign) 
    except Exception as e: 
     print("ERROR ", e) 
    return shaHashed 


if __name__ == '__main__': 
    app.run() 

답변

1

요망 hmac 라이브러리에서 update 함수이고, 그 대신 문자열/유니 코드 바이트 (지칭 hmac에 문서를 체크 할 입력을 요구하는 이후

h.update(data) 

: UR hmac_base64_key 기능은 특정 호출 원인 update 서명의 경우 hashlib). 수정은 단순히처럼

그래서 것 같다 : 당신이 setHeaders에서 문자열로을 연결하고 이후 다시 문자열로 compute_hmac_base64 (shaHashed)의 반환 값을 변경해야합니다

h.update(data.encode("utf8")) # or other encoding you want to use 

주 .

(나는이 파이썬 3 태그를 추가 했으므로 코드에서 파이썬 2를 확인해도 파이썬 3 코드라고 가정하고 있음).

+0

감사합니다. – AND4011002849