简体   繁体   中英

base64 HMAC with SHA256 in Python

I am having a hard time creating a signature.

I am needing to make a signature using HMAC with SHA256 using a Checkout Request JSON and a secret key. I need to do it by concatenating signature, pipe character (|) and Checkout Request JSON and then encoding it with BASE64.

This is a formula I found in the documentations:

$signed_checkout_request = base64( hmac_sha256( $checkout_request, $private_key ) + "|" + $checkout_request )

I have made this based on some online code:

    import hashlib
    import hmac
    import base64

    checkout_request = '{"charge":{"amount":499,"currency":"EUR"}}'.encode('utf-8');
    private_key = b'44444444444';
    digest = hmac.new(private_key, msg=checkout_request, digestmod=hashlib.sha256).digest()

    signature = base64.b64encode(digest).decode()

However I am not sure how to get the "|" into it. I am also not sure if I am even on the right track if I am honest... I don't have much experience in this section and I have failed at googling.

private_key = 'blahblahblah'

checkout_request = json.dumps({"charge":{"amount":4999,"currency":"EUR"}}, sort_keys=True, separators=(",", ":"))

digest = hmac.new(private_key.encode(), msg=checkout_request.encode(), digestmod=hashlib.sha256,).hexdigest()

signature = base64.b64encode((digest + "|" + checkout_request).encode()).decode()

I was able to get it to work with that:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM