Creating hash
Creating hash values are one of the most important steps when using the Qvickly API. The hash value is used to verify the integrity of the data sent to the API. The hash value is created by converting the data section of the payload to a JSON string and then use the secret key creating a 512 bit hmac.
Example
Let's say that we have a payload that looks like this:
{
"data": {
"id": "123456",
"amount": 100,
"currency": "SEK"
}
}
The JSON string of the data section would look like this:
{"id":"123456","amount":100,"currency":"SEK"}
In this case we assume that the secret key is 1234567890123456
.
<?php
$payload = [
"data" => [
"id" => "123456",
"amount" => 100,
"currency" => "SEK"
]
];
$secret = '1234567890123456';
$hash = hash_hmac('sha512', json_encode($payload["data"]), $secret);
print($hash);
import simplejson
import hmac
import hashlib
payload = {
"data": {
"id": "123456",
"amount": 100,
"currency": "SEK"
}
}
key = '1234567890123456'
hash_value = hmac.new(key.encode('utf-8'), simplejson.dumps(payload["data"], separators=(',', ':')).replace('/', '\\/').encode(), hashlib.sha512).hexdigest()
print(hash_value)
const { createHmac } = require('node:crypto');
const data = {
"data": {
"id": "123456",
"amount": 100,
"currency": "SEK"
}
};
const content = JSON.stringify(data["data"]);
const secret = "1234567890123456";
const hash = createHmac('sha512', secret).update(content).digest('hex');
console.log(hash);
import { hmac } from "https://deno.land/x/hmac/mod.ts";
const data = {
"data": {
"id": "123456",
"amount": 100,
"currency": "SEK"
}
};
const content = JSON.stringify(data["data"]);
const secret = "1234567890123456";
const hash = hmac("sha512", secret, content, "utf-8", "hex")
console.log(hash);
import { createHmac } from "crypto";
const data = {
"data": {
"id": "123456",
"amount": 100,
"currency": "SEK"
}
};
const content = JSON.stringify(data["data"]);
const secret = "1234567890123456";
const hash = createHmac('sha512', secret).update(content).digest('hex');
console.log(hash);
package main
import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"encoding/json"
)
type Test struct {
Id string `json:"id"`
Amount int `json:"amount"`
Currency string `json:"currency"`
}
func main() {
test := &Test{}
test.Id = "123456"
test.Amount = 100
test.Currency = "SEK"
data, _ := json.Marshal(test)
secret := "1234567890123456"
mac := hmac.New(sha512.New, []byte(secret))
mac.Write(data)
calculatedMac := mac.Sum(nil)
hexcode := hex.EncodeToString(calculatedMac)
println(hexcode)
}
namespace SimpleWork
{
using System;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
internal class Program
{
class Test
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("amount")]
public int Amount { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
}
public static void Main(string[] args)
{
Test test = new Test
{
Id = "123456",
Amount = 100,
Currency = "SEK"
};
string jsonData = JsonConvert.SerializeObject(test);
string secret = "1234567890123456";
using (HMACSHA512 hmac = new HMACSHA512(Encoding.UTF8.GetBytes(secret)))
{
byte[] data = Encoding.UTF8.GetBytes(jsonData);
byte[] calculatedMac = hmac.ComputeHash(data);
string hexcode = BitConverter.ToString(calculatedMac).Replace("-", "").ToLower();
Console.WriteLine(hexcode);
}
}
}
}
use ring::hmac;
use serde::{Serialize, Deserialize};
use serde_json;
#[derive(Serialize, Deserialize)]
struct MyObject {
id: String,
amount: i32,
currency: String,
}
fn calculate_hmac(key: &[u8], data: &[u8]) -> hmac::Tag {
let signing_key = hmac::Key::new(hmac::HMAC_SHA512, key);
hmac::sign(&signing_key, data)
}
fn main() {
let key = b"1234567890123456";
let my_object = MyObject {
id: String::from("123456"),
amount: 100,
currency: String::from("SEK"),
};
// Serialize the object to a JSON string
let data = serde_json::to_string(&my_object).expect("Serialization failed");
let hmac_result = calculate_hmac(key, data.as_bytes());
// Print the hexadecimal representation of the HMAC-SHA512 result
for byte in hmac_result.as_ref() {
print!("{:02x}", byte);
}
println!();
}
import java.security.MessageDigest;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) throws Exception {
// Create payload
Payload payload = new Payload("123456", 100, "SEK");
// Convert payload to JSON
Gson gson = new Gson();
String payloadJson = gson.toJson(payload);
// Generate hash using HMAC-SHA512
String secretKey = "1234567890123456";
String hash = generateHmacSHA512(payloadJson, secretKey);
// Print the hash
System.out.println(hash);
}
public static String generateHmacSHA512(String data, String key) throws Exception {
String algorithm = "HmacSHA512";
Mac mac = Mac.getInstance(algorithm);
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm);
mac.init(secretKey);
byte[] bytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
return result.toString();
}
static class Payload {
String id;
int amount;
String currency;
public Payload(String id, int amount, String currency) {
this.id = id;
this.amount = amount;
this.currency = currency;
}
}
}
This should result in the following hash value:
8dde708fea8cfcee68d6817975f37bf9b0c5412f3edfbd1d1d2bca629bd49f06a57bddcaac465ebe8306d25d6e1ff32e8a225c6b58ebef2ea39f51a6777f037a
Last modified: 13 September 2024