Use hmac.new() in Python3 - python-3.x

How can I use this function:
def generate_sig(endpoint, params, secret):
sig = endpoint
for key in sorted(params.keys()):
sig += '|%s=%s' % (key, params[key])
return hmac.new(secret, sig, sha256).hexdigest()
with these parameters:
endpoint = '/media/657988443280050001_25025320'
params = {
'access_token': 'fb2e77d.47a0479900504cb3ab4a1f626d174d2d',
'count': 10,
}
secret = '6dc1787668c64c939929c17683d7cb74'
In Python 3? Now I receive this error:
TypeError: key: expected bytes or bytearray, but got 'str'

This work for me:
def generate_sig(endpoint, params, secret):
sig = endpoint
for key in sorted(params.keys()):
sig += '|%s=%s' % (key, params[key])
return hmac.new(bytes(secret,encoding='ascii'),
bytes(sig,encoding='ascii'),
sha256).hexdigest()
This way you encode like bytes only to get the hash.

Related

NoneType' object has no attribute 'send error while mounting https session

I need mount session from specified ip address (192.168.100.40)
but getting next error:
response = self._session.send(request.prepare())
AttributeError: 'NoneType' object has no attribute 'send'
Problem in this two lines.if i removing mounting session parametrs
from
self.source_adapt = source.SourceAddressAdapter('192.168.100.40')
self._session = Session().mount('https://', self.source_adapt)
to self._session = Session() All is works but without binding of IP, that i need
What i doing wrong in my code ? :
import time
import urllib.parse
from typing import Optional, Dict, Any, List
from requests import Request, Session, Response
import hmac
from requests_toolbelt.adapters import source
class FtxClient:
_ENDPOINT = 'https://ftx.com/api/'
def __init__(self, api_key='my_key', api_secret='my_secret', subaccount_name=None) -> None:
self.source_adapt = source.SourceAddressAdapter('192.168.100.40')
self._session = Session().mount('https://', self.source_adapt)
self._api_key = api_key
self._api_secret = api_secret
self._subaccount_name = subaccount_name
def _post(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
return self._request('POST', path, json=params)
def _request(self, method: str, path: str, **kwargs) -> Any:
request = Request(method, self._ENDPOINT + path, **kwargs )
self._sign_request(request)
response = self._session.send(request.prepare())
return self._process_response(response)
def _sign_request(self, request: Request) -> None:
ts = int(time.time() * 1000)
prepared = request.prepare()
signature_payload = f'{ts}{prepared.method}{prepared.path_url}'.encode()
if prepared.body:
signature_payload += prepared.body
signature = hmac.new(self._api_secret.encode(), signature_payload, 'sha256').hexdigest()
request.headers['FTX-KEY'] = self._api_key
request.headers['FTX-SIGN'] = signature
request.headers['FTX-TS'] = str(ts)
if self._subaccount_name:
request.headers['FTX-SUBACCOUNT'] = urllib.parse.quote(self._subaccount_name)
def _process_response(self, response: Response) -> Any:
try:
data = response.json()
except ValueError:
response.raise_for_status()
raise
else:
if not data['success']:
raise Exception(data['error'])
return data['result']
def add_ip(self) -> dict:
return self._post('direct_access_settings/add_ip', {
'name': "'test_15.29.137.131'",
'ip': "15.29.137.131"
})
def main():
client = FtxClient()
add_ip = client.add_ip()
print(add_ip)
if __name__ == '__main__':
main()

Fernet in python, "token must be bytes"

Okay so this is my code:
#client.command(aliases=['d'], pass_context=True)
async def decrypt(ctx, arg, member=discord.Member):
key = b'xxxxxx'
f = Fernet(key)
decrypted = f.decrypt(arg)
channel = await member.create_dm()
await channel.send(f'Decrypted message: {decrypted}')
I insert a string after ctx, and it says TypeError: token must be bytes.
My arg is this (which is a byte, right?): b'gAAAAABgx22pwwjUHUA7KqV8jmZrXvocfC3VrHS_QrGCfCaEyj6f7cG1_K3NtbkADYiR4l8fq-DiqYJJk2k8n0jBUhDYsH2kNA=='
First of all, pass_context is deprecated. Second, no need to use create_dm; members are messageables, so you can do member.send. Third, discord.py interprets all arguments as strings by default. You'll need to use typehints (speaking of which, = is used to assign default values, not argument types). And fourth, this will send Decrypted message: b'meetmeatthepetstore', not Decrypted message: meetmeatthepetstore, so you'll want to decode the result. Here's the result:
#client.command(aliases=['d'])
async def decrypt(ctx, arg: bytes, member: discord.Member):
key = b'mycoolkey'
f = Fernet(key)
decrypted = f.decrypt(arg).decode('utf_8')
await member.send(f'Decrypted message: {decrypted}')

pyjwt raises TypeError

I'm using pyjwt as follows:
def encode_auth_token(self, user_id):
'''Generates the auth token.'''
try:
payload = {
'exp': datetime.utcnow() + datetime.timedelta(
days = current_app.config.get('TOKEN_EXPIRATION_DAYS'),
seconds = current_app.config.get('TOKEN_EXPIRATION_SECONDS')
),
'iat': datetime.datetime.utcnow(),
'sub': user_id
}
return jwt.encode(
payload,
current_app.config.get('SECRET_KEY'),
algorithm='HS256'
)
except Exception as e:
return e
the problem with this is that according to docs instance.encode() should return bytes and according to another resource it should return str. When I run it through unitttests:
auth_token = user.encode_auth_token(user.id)
self.assertTrue(isinstance(auth_token, str))
I get: AssertionError: False is not true and when I replace str with bytes I get the same error. So what type this method should be returning ?
its prolly returning byte data. If you can confirm that it does, you can force it return string by calling the decode method on the token instance itself.
token = jwt.encode(payload,secret).decode('utf-8')
return token

Argument 'algorithm' passed by position and keyword in method callp

I am trying to write a class and call it this is my code
import jwt
class generate_jwt():
def __init__(self):
self.name = 'jwt token manager'
def encode_with_hsa(self, secret, expiration_time, payload):
exp_time = {'exp': expiration_time}
return jwt.encode(payload, exp_time, secret, algorithm='HS256')
snake = generate_jwt()
so = {'secret':'ff'}
print(snake.encode_with_hsa('dd', 434234, so))
But this shows TypeError: encode() got multiple values for argument 'algorithm' when calling the class and returing the value
I fixed your code by doing something like:
import jwt
class generate_jwt():
def __init__(self):
self.name = 'jwt token manager'
def encode_with_hsa(self, secret, expiration_time, payload):
exp_time = {'exp': expiration_time}
return jwt.encode(payload, secret, algorithm='HS256', exp_time)
snake = generate_jwt()
so = {'secret':'ff'}
print(snake.encode_with_hsa('dd', 434234, so))
Checkout the definition of encode function here:
def encode(self,
payload, # type: Union[Dict, bytes]
key, # type: str
algorithm='HS256', # type: str
headers=None, # type: Optional[Dict]
json_encoder=None # type: Optional[Callable]
):
So, you have to go by the definition of the function, i.e. how the arguments are passed (order of the arguments).
Note: I am not sure where you need the exp_time. You can just remove it as it is optional.

Handling multipart/form-data with Python

I am trying to get the value of a POST with multipart/form-data to my backend.
Making the request:
files = {
'image': ('youtried.jpg', (open('youtried.jpg', 'rb')), 'image/jpg', {'Expires': '0'}),
'name': 'Deojeff'
}
r = requests.post('http://localhost/service/images', files=files)
print (r.text)
Handling the request:
def on_post(self, req, resp):
"""Creates an image."""
x = req.stream.read()
base64.b64encode(x)
helpers.write_json(resp, falcon.HTTP_200, {
'name': str(x)
})
How to get the value of 'name' ( in this case the value is 'Deojeff' ) in the on_post method of my class?
Try:
req.get_param('name')
returns the value of the param 'name'. Use req.params() to get the list of all the params with values.

Resources