Creating a signature. Code samples
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
class Main {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
String secret = "Oe8TBDzg4tatdq2cL9ojeEj3U3oWSCSC5fqOHAqaKVg";
String method = "POST";
String body = "{\"amount\":\"100\"}";
String date = "2019-01-09T11:24:40+00:00";
String path = "/api/auth/test";
String contentType = "application/json";
// 5173e4d02d8a761679b0165b87d9ee5f
String bodyMD5 = body.isEmpty() ? "" : md5hex(body);
// POST\n5173e4d02d8a761679b0165b87d9ee5f\napplication/json\n2019-01-09T11:24:40+00:00\n/api/auth/test
String stringToSign = String.join("\n", method, bodyMD5, contentType, date, path);
// fVYzUdYqZO1ozBeP3KQHFp9/Kno=
String signature = hmac(stringToSign, secret);
System.out.println(signature);
}
private static String md5hex(String str) throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest(str.getBytes(StandardCharsets.UTF_8));
return hex(bytes);
}
private static String hmac(String str, String secret) throws InvalidKeyException, NoSuchAlgorithmException {
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] result = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
String base64 = Base64.getEncoder().encodeToString(result);
return base64;
}
private static String hex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
class Test {
public static int Main() {
Test test = new Test("https://business-sandbox.cryptopay.me", "your_API_key", "your_API_secret");
Console.WriteLine(test.CreateInvoice("{\"price_amount\":\"0.5\",\"price_currency\":\"ETH\",\"pay_currency\":\"ETH\"}"));
Console.WriteLine(test.ListInvoices());
return 0;
}
private APIClient client;
public Test(string baseURL, string key, string secret)
{
APIAuth auth = new APIAuth(key, secret);
client = new APIClient(baseURL, auth);
}
public string CreateInvoice(string data)
{
return client.DoRequest("POST", DateTime.Now, "/api/invoices", data);
}
public string ListInvoices()
{
return client.DoRequest("GET", DateTime.Now, "/api/invoices");
}
}
class APIClient {
private string baseURL;
private APIAuth auth;
public APIClient(string url, APIAuth apiAuth)
{
baseURL = url;
auth = apiAuth;
}
public string DoRequest(string verb, DateTime date, string path, string data = "", string contentType = "application/json", List<KeyValuePair<string, string>> Headers = null)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL + path);
HttpWebResponse response;
StreamWriter sw;
StreamReader sr;
string dateStr;
string responseData;
request.Method = verb;
request.ContentType = contentType;
request.ContentLength = data.Length;
request.Date = date;
dateStr = date.ToUniversalTime().ToString("r");
request.Headers.Add("Authorization", auth.GenerateAuthorizationHeader(verb, data, contentType, dateStr, path));
if (verb != "GET") {
sw = new StreamWriter(request.GetRequestStream());
sw.Write(data);
sw.Close();
}
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
responseData = sr.ReadToEnd();
return (responseData);
}
}
class APIAuth {
private string key;
private string secret;
public APIAuth(string apikey, string apisecret)
{
key = apikey;
secret = apisecret;
}
public string GenerateAuthorizationHeader(string httpVerb, string jsonBodyStr, string httpContentType, string dateStr, string relativeUrl)
{
string signature = GenerateSigniture(httpVerb, jsonBodyStr, httpContentType, dateStr, relativeUrl);
return $"HMAC {key}:{signature}";
}
public string GenerateSigniture(string httpVerb, string jsonBodyStr, string httpContentType, string dateStr, string relativeUrl) {
string jsonBodyHash = String.IsNullOrEmpty(jsonBodyStr) ? "" : GetMD5Hash(jsonBodyStr);
string signitureData = string.Join("\n", httpVerb, jsonBodyHash, httpContentType, dateStr, relativeUrl);
byte[] apiSecretBytes = Encoding.UTF8.GetBytes(secret);
byte[] signitureBytes = Encoding.UTF8.GetBytes(signitureData);
var hmacsha1 = new HMACSHA1(apiSecretBytes, false);
byte[] resultBytes = hmacsha1.ComputeHash(signitureBytes);
return Convert.ToBase64String(resultBytes);
}
private string GetMD5Hash(string text) {
StringBuilder returnvalue = new StringBuilder();
MD5CryptoServiceProvider cryptoSP = new MD5CryptoServiceProvider();
byte[] HashBytes = Encoding.UTF8.GetBytes(text);
HashBytes = cryptoSP.ComputeHash(HashBytes);
foreach(byte bte in HashBytes)
returnvalue.Append(bte.ToString("x2").ToLower());
return returnvalue.ToString();
}
}
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text
Class Test
Public Shared Function Main() As Integer
Dim auth As APIAuth = New APIAuth("key", "secret")
Dim client As APIClient = New APIClient("https://business-sandbox.cryptopay.me", auth)
Dim path As String = "/api/invoices"
Dim data As String = "{""price_amount"":""0.5"",""price_currency"":""ETH"",""pay_currency"":""ETH""}"
Dim response As String = client.DoRequest(DateTime.Now, path, data)
Console.WriteLine(response)
Return 0
End Function
End Class
Class APIClient
Private baseURL As String
Private auth As APIAuth
Public Sub New(ByVal url As String, ByVal apiAuth As APIAuth)
baseURL = url
auth = apiAuth
End Sub
Public Function DoRequest(ByVal date As DateTime, ByVal path As String, ByVal Optional data As String = "", ByVal Optional contentType As String = "application/json", ByVal Optional Headers As List(Of KeyValuePair(Of String, String)) = Nothing, ByVal Optional verb As String = "POST") As String
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim request As HttpWebRequest = CType(WebRequest.Create(baseURL & path), HttpWebRequest)
Dim response As HttpWebResponse
Dim sw As StreamWriter
Dim sr As StreamReader
Dim dateStr As String
Dim responseData As String
request.Method = verb
request.ContentType = contentType
request.ContentLength = data.Length
request.Date = date
dateStr = date.ToUniversalTime().ToString("r")
request.Headers.Add("Authorization", auth.GenerateAuthorizationHeader(verb, data, contentType, dateStr, path))
sw = New StreamWriter(request.GetRequestStream())
sw.Write(data)
sw.Close()
response = CType(request.GetResponse(), HttpWebResponse)
sr = New StreamReader(response.GetResponseStream())
responseData = sr.ReadToEnd()
Return (responseData)
End Function
End Class
Class APIAuth
Private key As String
Private secret As String
Public Sub New(ByVal apikey As String, ByVal apisecret As String)
key = apikey
secret = apisecret
End Sub
Public Function GenerateAuthorizationHeader(ByVal httpVerb As String, ByVal jsonBodyStr As String, ByVal httpContentType As String, ByVal dateStr As String, ByVal relativeUrl As String) As String
Dim signature As String = GenerateSigniture(httpVerb, jsonBodyStr, httpContentType, dateStr, relativeUrl)
Return $"HMAC {key}:{signature}"
End Function
Public Function GenerateSigniture(ByVal httpVerb As String, ByVal jsonBodyStr As String, ByVal httpContentType As String, ByVal dateStr As String, ByVal relativeUrl As String) As String
Dim jsonBodyHash As String = GetMD5Hash(jsonBodyStr)
Dim signitureData As String = String.Join(vbLf, httpVerb, jsonBodyHash, httpContentType, dateStr, relativeUrl)
Dim apiSecretBytes As Byte() = Encoding.UTF8.GetBytes(secret)
Dim signitureBytes As Byte() = Encoding.UTF8.GetBytes(signitureData)
Dim hmacsha1 = New HMACSHA1(apiSecretBytes, False)
Dim resultBytes As Byte() = hmacsha1.ComputeHash(signitureBytes)
Return Convert.ToBase64String(resultBytes)
End Function
Private Function GetMD5Hash(ByVal text As String) As String
Dim returnvalue As StringBuilder = New StringBuilder()
Dim cryptoSP As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim HashBytes As Byte() = Encoding.UTF8.GetBytes(text)
HashBytes = cryptoSP.ComputeHash(HashBytes)
For Each bte As Byte In HashBytes
returnvalue.Append(bte.ToString("x2").ToLower())
Next
Return returnvalue.ToString()
End Function
End Class
<?php
namespace Cryptopay;
class Authentication
{
private $apiKey;
private $apiSecret;
public function __construct($apiKey, $apiSecret) {
$this->apiKey = $apiKey;
$this->apiSecret= $apiSecret;
}
public function buildRequestHeaders($method, $path, $body, $headers) {
if ($body) {
$bodyHash = md5($body);
} else {
$bodyHash = '';
}
$date = $headers['Date'];
$contentType = $headers['Content-Type'];
$sigString = implode("\n", [$method, $bodyHash, $contentType, $date, $path]);
$signature = base64_encode(hash_hmac('sha1', $sigString, $this->apiSecret, true));
return [
'Authorization' => 'HMAC '.$this->apiKey.':'.$signature
];
}
}
api_key = 'DjlHuWlApznJ7vrhPBL0fA'
api_secret = '3pPl6TbsoRlz0FLpKM6r-UG788g4-Fk5d1v1gKdXAA8'
string_to_signature = [
'POST',
'ba3c4838768171e3a221a9d619f5440c',
'application/json',
'Tue, 25 Sep 2018 17:41:40 GMT',
'/api/invoices'
].join("\n")
digest = OpenSSL::Digest.new('sha1')
signature = OpenSSL::HMAC.digest(digest, api_secret, string_to_signature)
encoded_signature = Base64.strict_encode64(signature)
payload_MD5 = CryptoJS.MD5(request.data).toString();
date = new Date(Date.now()).toUTCString();
string_to_sign = "POST" + "\n" + payload_MD5 + "\n" + "application/json" + "\n" + date + "\n" + "/api/channels"
hmac = CryptoJS.HmacSHA1(string_to_sign, "MoJj8czcibe0kMBUc69O5AhlEI7oafGkLBjOgNaekLA");
signature = hmac.toString(CryptoJS.enc.Base64);
import requests
import json
import hmac
import hashlib
import base64
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
#########################################
### https://reference.cryptopay.me/ ###
#########################################
# Api keys
api_key = "your_API_key"
api_secret = "your_API_secret"
# Content type
content_type = "application/json"
# Date
payment_date = format_date_time(mktime(datetime.now().timetuple()))
# [Cryptopayme] Create payment
# https://reference.cryptopay.me/#tag/Invoices/operation/invoices.create
def create_invoice_payment_cryptopayme(price_amount, price_currency, pay_currency, custom_id, name, description):
if price_amount and price_currency and pay_currency:
payment_host = "https://business-sandbox.cryptopay.me"
payment_path = "/api/invoices"
payment_url = payment_host + payment_path
payment_data = {
"price_amount": str(price_amount),
"price_currency": str(price_currency),
"pay_currency": str(pay_currency),
}
body = json.dumps(payment_data)
bodyhash = hashlib.md5(str.encode(body)).hexdigest()
sigstring = "POST\n"
sigstring += bodyhash + "\n"
sigstring += content_type + "\n"
sigstring += payment_date + "\n"
sigstring += payment_path
digest = hmac.new(str.encode(api_secret), str.encode(sigstring), hashlib.sha1)
signature = base64.b64encode(digest.digest())
authorization = "HMAC " + api_key + ":" + signature.decode('utf-8')
headers = {
"Authorization": authorization,
"Content-Type": content_type,
"Date": payment_date,
}
# Log (Request headers)
f = open("request-log.json", "w")
f.write(json.dumps(headers))
f.write("\n")
f.write(body)
f.close()
# Request post
response = requests.post(payment_url, headers=headers, data=body)
# Log (Response)
# Log (Request headers)
f = open("response.json", "w")
f.write(response.text)
f.close()
if response.status_code == 201:
response_data = json.loads(response.text)
payment_redirect_url = response_data["data"]["hosted_page_url"]
return payment_redirect_url
else:
return None
else:
return None
print(create_invoice_payment_cryptopayme("10", "EUR", "XRP", "", "", ""))
Last updated