How to generate an HMAC-SHA256 hash in base64?

JamalT
Shopify Partner
2 0 1

I'm trying to generate an HMAC-SHA256 hash in base64 to use with a 3rd party integration. The hash needs to be appended to the end of the URL in an iFrame on the page, and is created from the URL query parameters and values.

 

I'm pretty sure I'm clashing with data types, where a hexadecimal value is being converted to UTF-8 and therefore affecting the base64 conversion. I'm reaching the end of my experience, so looking for some suggestions.

 

Example code:

{% assign queryString = "ShopifyID" | append: customer.id %}
{% assign secretKey = "[Shared secret]" %}

{% assign hashSignature = {{queryString | hmac_sha256: secretKey | base64_encode | url_encode}} %}

<iframe src="https://[Resource URL]?ShopifyID={{customer.id}}&signature={{hashSignature}}"></iframe>

 

The issue I have is that the signature generated in liquid does not match with the 3rd party, where the result should be 44 characters in length, however, the result I get from the liquid code above is 88.

I've run the same parameters through an external site as well as in javascript and these produce the same result as the third party. Jscript runs client-side, and I haven't been able to find a way to use this either due to iFrame load timing, or having the pass through the secret key to the browser.

 

Using some random number generators for the customer.id and secret key, I can get the following:

queryString = ShopifyID5184202623769

Secret Key = 9b98935d8fe6a6aa907046efdd070449

Expected output = Rjn1Ub1Mw2GGiCwclOqBzs4+LaB76dhPvsKqD0xda4I=

Liquid output = NDYzOWY1NTFiZDRjYzM2MTg2ODgyYzFjOTRlYTgxY2VjZTNlMmRhMDdiZTlkODRmYmVjMmFhMGY0YzVkNmI4Mg==

Replies 5 (5)

Schmidtc63
Shopify Partner
53 7 19

Did you ever figure this out? I'm running into the same issue.

JamalT
Shopify Partner
2 0 1

Sadly, no.

 

As best I can tell, these particular Liquid encryption libraries are not included in Shopify's Liquid.

 

Similarly, if you do find something, I would be happy to hear!

Schmidtc63
Shopify Partner
53 7 19

So, the hash is working fine. It's the conversion to base64. hmac generates a hex string. But, the liquid to Base64 is strictly text to Base64, not hex to base64. So, I did this:

 

{% liquid
   assign gcHash="some thing I want to hash" | hmac_sha256: "my secret code"
%} 

<script>
    gcHash=btoa(String.fromCharCode.apply(null, '{{ gcHash }}'.match(/\w{2}/g).map(function(a) { return parseInt(a, 16) })));
    customerEmail = '{{ customer.email }}';
</script>

 

That took care of it. I got the correct 44-byte hash I was looking for.

Christian52
Shopify Partner
2 0 0

I'm having the same issue but can't figure out where I need to paste this code to fix it 

 

Schmidtc63
Shopify Partner
53 7 19

In any theme liquid file where you need this.