Skip to main content

Set authentication


Each API request requires setting the following headers:

HeaderDescription
X-Api-KeyThe SHA256 hash from your public API key in Base64 format.
X-Api-SignatureThe query's serialized body. You must sign it with your private key according to the RSA-SHA256 method.

Code samples

The following code samples illustrate how to authenticate and send signed requests.

info

Recommend Go version is 1.21.1.

package main

import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
)

func main() {
// Your generated private key as a string
privateKeyString := "<<YOUR_PRIVATE_KEY>>"

// Decode the hex-encoded private key
decodedPrivateKey, err := hex.DecodeString(privateKeyString)
if err != nil {
panic(err)
}

// Parse the PKCS8 private key
privateKey, err := x509.ParsePKCS8PrivateKey(decodedPrivateKey)
if err != nil {
panic(err)
}
rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey)
if !ok {
panic("Failed to cast to RSA Private Key")
}

// Marshal the public key to DER format
publicDER := x509.MarshalPKCS1PublicKey(&rsaPrivateKey.PublicKey)

// Define the message payload
message := map[string]interface{}{
"jsonrpc": "2.0",
"id": "test",
"method": "getStatus",
"params": map[string]string{
"id": "pgj********2minj",
},
}
messageBytes, err := json.Marshal(message)
if err != nil {
panic(err)
}

// Sign the message with the RSA private key
hashed := sha256.Sum256(messageBytes)
signature, err := rsa.SignPKCS1v15(rand.Reader, rsaPrivateKey, crypto.SHA256, hashed[:])
if err != nil {
panic(err)
}

// Prepare the HTTP POST request
client := &http.Client{}
req, err := http.NewRequest("POST", "https://api.criptointercambio.com/v2", bytes.NewReader(messageBytes))
if err != nil {
panic(err)
}

// Set request headers
hash := sha256.Sum256(publicDER)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Api-Key", base64.StdEncoding.EncodeToString(hash[:]))
req.Header.Set("X-Api-Signature", base64.StdEncoding.EncodeToString(signature))

// Send the request
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

// Check if the status code is 401
if resp.StatusCode == http.StatusUnauthorized {
fmt.Println("Received status code 401 Unauthorized")
}

// Read and display the response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(respBody))
}