def sign_string(self, string_to_sign): if self._hmac_256: hmac = self._hmac_256.copy() else: hmac = self._hmac.copy() hmac.update(string_to_sign) return base64.encodestring(hmac.digest()).strip()
def _mac(self, fh): hmac = self.hmac.copy() d = self._read(fh, BUFFER_SIZE, 0) while d: hmac.update(d) d = self._read(fh, BUFFER_SIZE) return hmac.digest()[:MAC_SIZE]
def calc_signature_2(self, params, verb, path): boto.log.debug('using calc_signature_2') string_to_sign = '%s\n%s\n%s\n' % (verb, self.server_name().lower(), path) if self.hmac_256: hmac = self.hmac_256.copy() params['SignatureMethod'] = 'HmacSHA256' else: hmac = self.hmac.copy() params['SignatureMethod'] = 'HmacSHA1' keys = params.keys() keys.sort() pairs = [] for key in keys: val = self.get_utf8_value(params[key]) pairs.append( urllib.quote(key, safe='') + '=' + urllib.quote(val, safe='-_~')) qs = '&'.join(pairs) boto.log.debug('query string: %s' % qs) string_to_sign += qs boto.log.debug('string_to_sign: %s' % string_to_sign) hmac.update(string_to_sign) b64 = base64.b64encode(hmac.digest()) boto.log.debug('len(b64)=%d' % len(b64)) boto.log.debug('base64 encoded digest: %s' % b64) return (qs, b64)
def _calc_signature(self, params, verb, path, server_name): boto.log.debug('using _calc_signature_2') string_to_sign = '%s\n%s\n%s\n' % (verb, server_name.lower(), path) if self._hmac_256: hmac = self._hmac_256.copy() params['SignatureMethod'] = 'HmacSHA256' else: hmac = self._hmac.copy() params['SignatureMethod'] = 'HmacSHA1' keys = params.keys() keys.sort() pairs = [] for key in keys: val = boto.utils.get_utf8_value(params[key]) pairs.append(urllib.quote(key, safe='') + '=' + urllib.quote(val, safe='-_~')) qs = '&'.join(pairs) boto.log.debug('query string: %s' % qs) string_to_sign += qs boto.log.debug('string_to_sign: %s' % string_to_sign) hmac.update(string_to_sign) b64 = base64.b64encode(hmac.digest()) boto.log.debug('len(b64)=%d' % len(b64)) boto.log.debug('base64 encoded digest: %s' % b64) return (qs, b64)
def _calc_signature(self, params, verb, path, server_name): boto.log.debug("using _calc_signature_2") string_to_sign = "%s\n%s\n%s\n" % (verb, server_name.lower(), path) if self._hmac_256: hmac = self._hmac_256.copy() params["SignatureMethod"] = "HmacSHA256" else: hmac = self._hmac.copy() params["SignatureMethod"] = "HmacSHA1" if self._provider.security_token: params["SecurityToken"] = self._provider.security_token keys = params.keys() keys.sort() pairs = [] for key in keys: val = boto.utils.get_utf8_value(params[key]) pairs.append(urllib.quote(key, safe="") + "=" + urllib.quote(val, safe="-_~")) qs = "&".join(pairs) boto.log.debug("query string: %s" % qs) string_to_sign += qs boto.log.debug("string_to_sign: %s" % string_to_sign) hmac.update(string_to_sign) b64 = base64.b64encode(hmac.digest()) boto.log.debug("len(b64)=%d" % len(b64)) boto.log.debug("base64 encoded digest: %s" % b64) return (qs, b64)
def _mac(self, fh, h): pos, hmac = MAC_SIZE, self.hmac.copy() d = self._read(fh, BUFFER_SIZE, pos) while d: hmac.update(self._dec(h, pos, d)) pos, d = pos + len(d), self._read(fh, BUFFER_SIZE) return hmac.digest()[:MAC_SIZE]
def sign_string(self, string_to_sign): boto.log.debug('Canonical: %s' % string_to_sign) if self._hmac_256: hmac = self._hmac_256.copy() else: hmac = self._hmac.copy() hmac.update(string_to_sign) return base64.encodestring(hmac.digest()).strip()
def request_new_test(self, duration, interval, hmac_hex, raw_data=False): """Request a new test instance. This will allocate a new ITGRecv instance and parse the log file it produces. The results of this can then be retrieved with get_test_results() after the test has run. The parameters are: duration: Requested test duration in seconds. The ITGRecv instance will be killed after this time has passed (+ a grace period of five seconds). interval: The requested interval for data points, in milliseconds (passed to ITGDec). hmac_hex: A hexadecimal HMAC-SHA256 of the two other parameters computed by concatenating their ASCII representations. The HMAC secret is configured by the operator of the control server instance. raw_data: Whether to store and return the raw text log from ITGDec (i.e. the output of ITGDec -l) The return value is a dictionary with the following keys: status: 'OK' if everything went well, 'Error' otherwise. message: Set if status is 'Error'; contains an error message. test_id: The assigned test ID, to be passed to get_test_results() after the duration has expired. port: The control server port of the ITGRecv instance. The sender is expected to use port+1 for the data connection. """ self._collect_garbage() duration = int(duration) interval = int(interval) hmac = self.hmac.copy() hmac.update(str(duration).encode()) hmac.update(str(interval).encode()) if hmac.hexdigest() != hmac_hex: return {"status": "Error", "message": "HMAC authentication failure."} if duration <= 0 or interval <= 0: return {"status": "Error", "message": "Duration and interval must be positive integers."} if duration > self.max_test_time: return {"status": "Error", "message": "Maximum test time of %d seconds exceeded." % self.max_test_time} if interval > duration * 1000: return {"status": "Error", "message": "Interval must be <= duration."} if len(self.children) >= self.max_instances: return {"status": "Error", "message": "Too many concurrent instances running. " "Try again later."} test_id = "".join(random.sample(ALPHABET, self.id_length)) # Need one port for control, one for data (if the data stream is TCP). port = self.current_port self.current_port += 2 return self._spawn_receiver(test_id, duration, interval, port, raw_data)
def add_aws_auth_header(self, headers, method, path): if not headers.has_key('Date'): headers['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()) c_string = boto.utils.canonical_string(method, path, headers) boto.log.debug('Canonical: %s' % c_string) hmac = self.hmac.copy() hmac.update(c_string) b64_hmac = base64.encodestring(hmac.digest()).strip() headers['Authorization'] = "AWS %s:%s" % (self.aws_access_key_id, b64_hmac)
def add_aws_auth_header(self, headers, method, path): path = self.get_path(path) if not headers.has_key("Date"): headers["Date"] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()) c_string = boto.utils.canonical_string(method, path, headers, None, self.provider) boto.log.debug("Canonical: %s" % c_string) hmac = self.hmac.copy() hmac.update(c_string) b64_hmac = base64.encodestring(hmac.digest()).strip() auth_hdr = self.provider.auth_header headers["Authorization"] = "%s %s:%s" % (auth_hdr, self.aws_access_key_id, b64_hmac)
def getSignedUrl(base_url, params, timestamp=None): global HMAC hmac = HMAC.copy() # Add a ISO 8601 compliant timestamp (in GMT) if timestamp: params["Timestamp"] = timestamp else: params["Timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) # params['SignatureVersion']='1' # Sort the URL parameters by key keys = params.keys() # keys.sort(cmp = lambda x, y: cmp(x.lower(), y.lower())) keys.sort() # Reconstruct the URL parameters and encode them pairs = [] for key in keys: # val = urllib.quote(params[key]) val = params[key] pairs.append(key + "=" + val) url_string = "&".join(pairs) url_string = url_string.replace("+", "%20") url_string = url_string.replace(":", "%3A") # Construct the string to sign urlparts = base_url.split("/") string_to_sign = """GET %s /%s/%s %s""" % ( urlparts[2], urlparts[3], urlparts[4], url_string, ) url_string = url_string.replace(";", urllib.quote(";")) # Sign the request hmac.update(string_to_sign) signature = hmac.digest() # Base64 encode the signature signature = base64.encodestring(signature).strip() signature = signature.replace("+", "%2B") signature = signature.replace("=", "%3D") signature = signature.replace("/", "%2F") # Make the signature URL safe url_string += "&Signature=%s" % signature return "%s?%s" % (base_url, url_string)
def calc_signature_1(self, params): boto.log.debug("using calc_signature_1") hmac = self.hmac.copy() keys = params.keys() keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower())) pairs = [] for key in keys: hmac.update(key) val = self.get_utf8_value(params[key]) hmac.update(val) pairs.append(key + "=" + urllib.quote(val)) qs = "&".join(pairs) return (qs, base64.b64encode(hmac.digest()))
def _calc_signature(self, params, *args): boto.log.debug('using _calc_signature_1') hmac = self._get_hmac() keys = params.keys() keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower())) pairs = [] for key in keys: hmac.update(key.encode('utf-8')) val = boto.utils.get_utf8_value(params[key]) hmac.update(val) pairs.append(key + '=' + urllib.parse.quote(val)) qs = '&'.join(pairs) return (qs, base64.b64encode(hmac.digest()))
def _calc_signature(self, params, *args): boto.log.debug('using _calc_signature_0') hmac = self._get_hmac() s = params['Action'] + params['Timestamp'] hmac.update(s.encode('utf-8')) keys = params.keys() keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower())) pairs = [] for key in keys: val = get_utf8able_str(params[key]) pairs.append(key + '=' + urllib.parse.quote(val)) qs = '&'.join(pairs) return (qs, base64.b64encode(hmac.digest()))
def calc_signature_1(self, params): boto.log.debug('using calc_signature_1') hmac = self.hmac.copy() keys = params.keys() keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower())) pairs = [] for key in keys: hmac.update(key) val = self.get_utf8_value(params[key]) hmac.update(val) pairs.append(key + '=' + urllib.quote(val)) qs = '&'.join(pairs) return (qs, base64.b64encode(hmac.digest()))
def calc_signature_0(self, params): boto.log.debug('using calc_signature_0') hmac = self.hmac.copy() s = params['Action'] + params['Timestamp'] hmac.update(s) keys = params.keys() keys.sort(cmp = lambda x, y: cmp(x.lower(), y.lower())) pairs = [] for key in keys: val = self.get_utf8_value(params[key]) pairs.append(key + '=' + urllib.quote(val)) qs = '&'.join(pairs) return (qs, base64.b64encode(hmac.digest()))
def _calc_signature(self, params, *args): boto.log.debug("using _calc_signature_0") hmac = self._get_hmac() s = params["Action"] + params["Timestamp"] hmac.update(s) keys = params.keys() keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower())) pairs = [] for key in keys: val = boto.utils.get_utf8_value(params[key]) pairs.append(key + "=" + urllib.quote(val)) qs = "&".join(pairs) return (qs, base64.b64encode(hmac.digest()))
def _calc_signature(self, params, *args): boto.log.debug('using _calc_signature_1') hmac = self._get_hmac() keys = list(params.keys()) keys.sort(key=lambda x: x.lower()) pairs = [] for key in keys: hmac.update(key.encode('utf-8')) val = get_utf8able_str(params[key]).encode('utf-8') hmac.update(val) pairs.append(key + '=' + urllib.parse.quote(val)) qs = '&'.join(pairs) return (qs, base64.b64encode(hmac.digest()))
def _calc_signature(self, params, *args): boto.log.debug('using _calc_signature_0') hmac = self._hmac.copy() s = params['Action'] + params['Timestamp'] hmac.update(s) keys = params.keys() keys.sort(key=str.lower) pairs = [] for key in keys: val = boto.utils.get_utf8_value(params[key]) pairs.append(key + '=' + quote(val)) qs = '&'.join(pairs) return (qs, base64.b64encode(hmac.digest()))
def _calc_signature(self, params, *args): boto.log.debug('using _calc_signature_1') hmac = self._hmac.copy() keys = params.keys() keys.sort(cmp = lambda x, y: cmp(x.lower(), y.lower())) pairs = [] for key in keys: hmac.update(key) val = boto.utils.get_utf8_value(params[key]) hmac.update(val) pairs.append(key + '=' + urllib.quote(val)) qs = '&'.join(pairs) return (qs, base64.b64encode(hmac.digest()))
def _calc_signature(self, params, *args): boto.log.debug('using _calc_signature_1') hmac = self._get_hmac() keys = list(params.keys()) keys.sort(key=lambda x: x.lower()) pairs = [] for key in keys: hmac.update(key.encode('utf-8')) val = boto.utils.get_utf8_value(params[key]) hmac.update(val) pairs.append(key + '=' + urllib.parse.quote(val)) qs = '&'.join(pairs) return (qs, base64.b64encode(hmac.digest()))
def _calc_signature(self, params, *args): txboto.log.debug('using _calc_signature_0') hmac = self._get_hmac() s = params['Action'] + params['Timestamp'] hmac.update(s.encode('utf-8')) keys = params.keys() keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower())) pairs = [] for key in keys: val = txboto.utils.get_utf8_value(params[key]) pairs.append(key + '=' + quote(val)) qs = '&'.join(pairs) return (qs, base64.b64encode(hmac.digest()))
def getSignedUrl(base_url, params, timestamp=None): global HMAC hmac = HMAC.copy() # Add a ISO 8601 compliant timestamp (in GMT) if timestamp: params['Timestamp'] = timestamp else: params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) #params['SignatureVersion']='1' # Sort the URL parameters by key keys = params.keys() #keys.sort(cmp = lambda x, y: cmp(x.lower(), y.lower())) keys.sort() # Reconstruct the URL parameters and encode them pairs = [] for key in keys: #val = urllib.quote(params[key]) val = params[key] pairs.append(key + '=' + val) url_string = '&'.join(pairs) url_string = url_string.replace('+', "%20") url_string = url_string.replace(':', "%3A") #Construct the string to sign urlparts = base_url.split('/') string_to_sign = """GET %s /%s/%s %s""" % (urlparts[2], urlparts[3], urlparts[4], url_string) url_string = url_string.replace(';', urllib.quote(';')) # Sign the request hmac.update(string_to_sign) signature = hmac.digest() # Base64 encode the signature signature = base64.encodestring(signature).strip() signature = signature.replace('+', '%2B') signature = signature.replace('=', '%3D') signature = signature.replace('/', '%2F') # Make the signature URL safe url_string += "&Signature=%s" % signature return "%s?%s" % (base_url, url_string)
def calc_signature(self, args): scheme, host, port = requests.packages.urllib3.get_host(args['url']) string_to_sign = '%s\n%s\n%s\n' % (args['method'], host, '/') hmac = self.hmac.copy() args['params']['SignatureMethod'] = 'HmacSHA256' if self.credentials.token: args['params']['SecurityToken'] = self.credentials.token sorted_params = sorted(args['params']) pairs = [] for key in sorted_params: value = args['params'][key] pairs.append(quote(key, safe='') + '=' + quote(value, safe='-_~')) qs = '&'.join(pairs) string_to_sign += qs print('string_to_sign') print(string_to_sign) hmac.update(string_to_sign.encode('utf-8')) b64 = base64.b64encode(hmac.digest()).strip().decode('utf-8') return (qs, b64)
def _calc_signature(self, params, headers, verb, path): boto.log.debug('using euca_signature') string_to_sign = '%s\n%s\n%s\n' % (verb, headers['Date'], path) keys = params.keys() keys.sort() pairs = [] for key in keys: val = params[key] pairs.append(urllib.quote(key, safe='') + '=' + urllib.quote(val, safe='-_~')) qs = '&'.join(pairs) boto.log.debug('query string: %s' % qs) string_to_sign += qs hmac = self.hmac.copy() hmac.update(string_to_sign) sha_manifest = hashlib.sha1() sha_manifest.update(string_to_sign) private_key = M2Crypto.RSA.load_key(self.private_key_path) signature_value = private_key.sign(sha_manifest.digest()) b64 = base64.b64encode(signature_value) boto.log.debug('len(b64)=%d' % len(b64)) boto.log.debug('base64 encoded digest: %s' % b64) return (qs, b64)
def _calc_signature(self, params, headers, verb, path): boto.log.debug('using euca_signature') string_to_sign = '%s\n%s\n%s\n' % (verb, headers['Date'], path) keys = list(params.keys()) keys.sort() pairs = [] for key in keys: val = params[key] pairs.append(urllib.parse.quote(key, safe='') + '=' + urllib.parse.quote(val, safe='-_~')) qs = '&'.join(pairs) boto.log.debug('query string: %s' % qs) string_to_sign += qs hmac = self.hmac.copy() hmac.update(string_to_sign) sha_manifest = hashlib.sha1() sha_manifest.update(string_to_sign) private_key = crypto.RSA.load_key(self.private_key_path) signature_value = private_key.sign(sha_manifest.digest()) b64 = base64.b64encode(signature_value) boto.log.debug('len(b64)=%d' % len(b64)) boto.log.debug('base64 encoded digest: %s' % b64) return (qs, b64)
def _calc_signature(self, params, verb, path, server_name): boto.log.debug('using _calc_signature_2') string_to_sign = '%s\n%s\n%s\n' % (verb, server_name.lower(), path) hmac = self._get_hmac() params['SignatureMethod'] = self.algorithm() if self._provider.security_token: params['SecurityToken'] = self._provider.security_token keys = sorted(params.keys()) pairs = [] for key in keys: val = boto.utils.get_utf8_value(params[key]) pairs.append(urllib.quote(key, safe='') + '=' + urllib.quote(val, safe='-_~')) qs = '&'.join(pairs) boto.log.debug('query string: %s' % qs) string_to_sign += qs boto.log.debug('string_to_sign: %s' % string_to_sign) hmac.update(string_to_sign) b64 = base64.b64encode(hmac.digest()) boto.log.debug('len(b64)=%d' % len(b64)) boto.log.debug('base64 encoded digest: %s' % b64) return (qs, b64)
def _calc_signature(self, params, verb, path, server_name): boto.log.debug('using _calc_signature_2') string_to_sign = '%s\n%s\n%s\n' % (verb, server_name.lower(), path) hmac = self._get_hmac() params['SignatureMethod'] = self.algorithm() if self._provider.security_token: params['SecurityToken'] = self._provider.security_token keys = sorted(params.keys()) pairs = [] for key in keys: val = boto.utils.get_utf8_value(params[key]) pairs.append(urllib.parse.quote(key, safe='') + '=' + urllib.parse.quote(val, safe='-_~')) qs = '&'.join(pairs) boto.log.debug('query string: %s' % qs) string_to_sign += qs boto.log.debug('string_to_sign: %s' % string_to_sign) hmac.update(string_to_sign.encode('utf-8')) b64 = base64.b64encode(hmac.digest()) boto.log.debug('len(b64)=%d' % len(b64)) boto.log.debug('base64 encoded digest: %s' % b64) return (qs, b64)
def sign_string(self, to_sign): hmac = self.hmac.copy() hmac.update(to_sign) return base64.b64encode(hmac.digest())
def hash(self, value): hmac = self.newHMAC() hmac.update(value) return hmac.digest()
T = arraysA[i] * QBj U = str(T.x) + str(T.y) + "NoNeedToRunAndHide" U = str.encode(U) K_ENC = SHA3_256.new(U) K_ENC = K_ENC.digest() K_MAC = SHA3_256.new(K_ENC) K_MAC = K_MAC.digest() # Encyption cipher = AES.new(K_ENC, AES.MODE_CTR) ctext = str.encode(mesg) ctext = cipher.encrypt(ctext) #hmac calculation hmac = HMAC.new(K_MAC, digestmod=SHA256) hmac = hmac.update(ctext) hmac = hmac.digest() msg = cipher.nonce + ctext + hmac msg = int.from_bytes(msg, byteorder="big") ### Send message to student B mes = {'ID_A': stuID, 'ID_B': stuID_B, 'I': i, 'J': j, 'MSG': msg} response = requests.put('{}/{}'.format(API_URL, "SendMsg"), json=mes) print(response.json()) ''' ## Get your message mes = {'ID_A': stuID, 'S': s, 'H': h} response = requests.get('{}/{}'.format(API_URL, "ReqMsg_PH3"), json = mes) print(response.json()) if(response.ok): ## Decrypt message res = response.json()
def s3_authorization(self, headers, verb, path): c_string = boto.utils.canonical_string(verb, path, headers) hmac = self.hmac.copy() hmac.update(c_string) b64_hmac = base64.encodestring(hmac.digest()).strip() return b64_hmac
def request_new_test(self, duration, interval, hmac_hex): """Request a new test instance. This will allocate a new ITGRecv instance and parse the log file it produces. The results of this can then be retrieved with get_test_results() after the test has run. The parameters are: duration: Requested test duration in seconds. The ITGRecv instance will be killed after this time has passed (+ a grace period of five seconds). interval: The requested interval for data points, in milliseconds (passed to ITGDec). hmac_hex: A hexadecimal HMAC-SHA256 of the two other parameters computed by concatenating their ASCII representations. The HMAC secret is configured by the operator of the control server instance. The return value is a dictionary with the following keys: status: 'OK' if everything went well, 'Error' otherwise. message: Set if status is 'Error'; contains an error message. test_id: The assigned test ID, to be passed to get_test_results() after the duration has expired. port: The control server port of the ITGRecv instance. The sender is expected to use port+1 for the data connection. """ self._collect_garbage() duration = int(duration) interval = int(interval) hmac = self.hmac.copy() hmac.update(str(duration).encode()) hmac.update(str(interval).encode()) if hmac.hexdigest() != hmac_hex: return { 'status': 'Error', 'message': "HMAC authentication failure." } if duration <= 0 or interval <= 0: return { 'status': 'Error', 'message': "Duration and interval must be positive integers." } if duration > self.max_test_time: return { 'status': 'Error', 'message': "Maximum test time of %d seconds exceeded." % self.max_test_time } if interval > duration * 1000: return { 'status': 'Error', 'message': "Interval must be <= duration." } if len(self.children) >= self.max_instances: return { 'status': 'Error', 'message': "Too many concurrent instances running. Try again later." } test_id = "".join(random.sample(ALPHABET, self.id_length)) # Need one port for control, one for data (if the data stream is TCP). port = self.current_port self.current_port += 2 return self._spawn_receiver(test_id, duration, interval, port)
U = str(T.x)+str(T.y)+"NoNeedToRunAndHide" U = str.encode(U) K_ENC = SHA3_256.new(U) K_ENC = K_ENC.digest() K_MAC = SHA3_256.new(K_ENC) K_MAC = K_MAC.digest() # Encyption cipher = AES.new(K_ENC, AES.MODE_CTR) ctext=str.encode(mesg) ctext=cipher.encrypt(ctext) print("ctext:",ctext) #hmac calculation is missing hmac=HMAC.new(K_MAC,digestmod=SHA256) hmac=hmac.update(str.encode(str(ctext))) hmac=hmac.digest() print("hmac:",hmac) msg = cipher.nonce + ctext + hmac print("nonce+ctext+hmac:",msg) msg = int.from_bytes(msg, byteorder="big") print("int of the ctext:",msg) ### Send message to student B mes = {'ID_A': stuID, 'ID_B':stuID_B, 'I': i, 'J':j, 'MSG': msg} response = requests.put('{}/{}'.format(API_URL, "SendMsg"), json = mes) print(response.json()) ## Get your message mes = {'ID_A': stuID, 'S': s, 'H': h} response = requests.get('{}/{}'.format(API_URL, "ReqMsg_PH3"), json = mes)