Authentication overview

Bitcambio, a cryptocurrency exchange founded in 2014, facilitates the buying and selling of Bitcoin for Brazilian users with Brazilian Real (BRL). To interact programmatically with Bitcambio's platform, developers utilize an authentication system primarily based on API keys. This system is designed to secure transactions and user data, aligning with data protection regulations such as LGPD in Brazil.

Authentication on Bitcambio's API involves generating a unique pair of credentials: an API Key and an API Secret. The API Key identifies the application making the request, while the API Secret is used to sign requests, verifying their authenticity and integrity. This method is common across financial APIs to prevent unauthorized access and ensure that requests originate from legitimate sources. The integrity of these credentials is paramount for maintaining the security of an integrated application.

The API supports various operations, including account balance inquiries, order placement, and transaction history retrieval. Each request sent to the API must include specific authentication headers, ensuring that only authenticated and authorized users can perform actions on their accounts. Adherence to these authentication protocols is critical for developers building applications that integrate with Bitcambio's core products, such as its fiat-to-crypto exchange services.

Supported authentication methods

Bitcambio's API primarily supports an API Key and Secret-based authentication mechanism. This method is widely adopted in the API economy for its balance of security and ease of implementation. It involves a cryptographic signature process for each request, ensuring both authenticity and data integrity. While OAuth 2.0 is a prevalent standard for delegated authorization across many APIs, Bitcambio's direct API access streamlines integration for server-to-server communication where the application directly manages user credentials.

The core components of Bitcambio's authentication are:

  • API Key: A public identifier for your application. It is included directly in the request headers or parameters.
  • API Secret: A private key used to generate a cryptographic signature for each request. This secret must never be exposed publicly or transmitted directly in requests.
  • Signature: A hash generated using the API Secret, request parameters, and a timestamp. This signature is included in the request to prove its authenticity and that the request has not been tampered with. The HMAC-SHA256 algorithm is typically used for this purpose, a standard for message authentication codes as described by the IETF in RFC 2104.

This method ensures that even if an API Key is intercepted, the lack of the corresponding API Secret prevents an attacker from forging valid requests. The inclusion of a timestamp in the signature calculation also helps prevent replay attacks, where malicious actors attempt to resend old, valid requests.

Here's a table summarizing the authentication method:

Method When to Use Security Level
API Key & Secret (HMAC-SHA256) Server-to-server communication, programmatic trading, account management High (with proper secret management and IP whitelisting)

Getting your credentials

To obtain API credentials for Bitcambio, you must first have an active and verified Bitcambio account. The process typically involves accessing the API management section within your user dashboard on the Bitcambio website.

  1. Log In: Navigate to the Bitcambio homepage and log in to your account.
  2. Access API Settings: Locate the 'API' or 'Developers' section within your account settings or profile dashboard. The exact path may vary, so refer to the official Bitcambio documentation for precise navigation.
  3. Generate New Keys: Within the API settings, you will find an option to generate new API keys. This process typically creates both an API Key (public) and an API Secret (private).
  4. Record Your Secret Key: The API Secret is usually displayed only once upon generation. It is crucial to copy and store this secret securely immediately. If lost, you may need to revoke the existing key pair and generate a new one, as the secret cannot be retrieved.
  5. Configure Permissions (Optional but Recommended): Some platforms allow you to set specific permissions for your API keys (e.g., read-only access, trading access, withdrawal access). Configure these permissions to grant only the necessary access level for your application. Limiting permissions reduces the impact of a compromised key.
  6. IP Whitelisting (Optional but Recommended): For enhanced security, Bitcambio may offer an option to whitelist specific IP addresses that are permitted to use your API keys. This restricts API access to known servers, significantly reducing the risk of unauthorized use.

After generating your credentials, ensure they are stored in a secure environment, such as environment variables, a secrets manager, or a secure configuration file, and never hardcoded directly into your application's source code.

Authenticated request example

An authenticated request to the Bitcambio API involves constructing a request, signing it with your API Secret, and including the signature along with your API Key in the request headers or body. The exact parameters and signing process details are critical and should be confirmed with Bitcambio's official API documentation.

Below is a conceptual example of how an authenticated request might be structured, assuming a common HMAC-SHA256 signing mechanism.

Assumptions:

  • API_KEY: Your public API Key.
  • API_SECRET: Your private API Secret.
  • timestamp: Current Unix timestamp in milliseconds.
  • request_method: HTTP method (e.g., GET, POST).
  • request_path: The API endpoint path (e.g., /api/v1/account/balance).
  • request_body: The JSON request body (for POST/PUT requests), or an empty string for GET requests.

Signature Generation Steps:

  1. Concatenate the timestamp, request method, request path, and request body. (e.g., timestamp + method + path + body).
  2. Hash the concatenated string using HMAC-SHA256 with your API Secret as the key.
  3. Encode the resulting hash, typically in hexadecimal or Base64.

Conceptual Python Example (for illustration):


import hmac
import hashlib
import time
import json
import requests

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
BASE_URL = "https://api.bitcambio.com.br"

def create_signed_request(method, path, body=None):
    timestamp = str(int(time.time() * 1000))
    
    # Prepare the string to sign
    string_to_sign = timestamp + method.upper() + path
    if body:
        body_str = json.dumps(body, separators=(',', ':')) # Ensure compact JSON
        string_to_sign += body_str
    else:
        body_str = "" # For GET requests, body is empty

    # Generate HMAC-SHA256 signature
    signature = hmac.new(API_SECRET.encode('utf-8'), 
                         string_to_sign.encode('utf-8'), 
                         hashlib.sha256).hexdigest()

    headers = {
        "Content-Type": "application/json",
        "X-Bitcambio-API-Key": API_KEY,
        "X-Bitcambio-Timestamp": timestamp,
        "X-Bitcambio-Signature": signature
    }

    url = BASE_URL + path

    if method.upper() == "GET":
        response = requests.get(url, headers=headers)
    elif method.upper() == "POST":
        response = requests.post(url, headers=headers, data=body_str)
    else:
        raise ValueError("Unsupported HTTP method")

    response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
    return response.json()

# Example usage: Get account balance
try:
    balance_data = create_signed_request("GET", "/api/v1/account/balance")
    print("Account Balance:", balance_data)
except requests.exceptions.HTTPError as e:
    print(f"HTTP Error: {e.response.status_code} - {e.response.text}")
except Exception as e:
    print(f"An error occurred: {e}")

# Example usage: Place a limit buy order (conceptual)
# order_body = {
#     "symbol": "BTCBRL",
#     "side": "BUY",
#     "type": "LIMIT",
#     "price": "100000.00",
#     "quantity": "0.001"
# }
# try:
#     order_response = create_signed_request("POST", "/api/v1/order", body=order_body)
#     print("Order Placed:", order_response)
# except requests.exceptions.HTTPError as e:
#     print(f"HTTP Error: {e.response.status_code} - {e.response.text}")
# except Exception as e:
#     print(f"An error occurred: {e}")

Important Note: This is a generalized example. Always consult the official Bitcambio API documentation for the exact signing procedures, header names, endpoint paths, and data formats, as these can vary significantly between API versions and platforms. The Credential Management API, while not directly applicable to server-side API key management, illustrates the importance of secure credential handling in web environments.

Security best practices

Securing your Bitcambio API integration is crucial to protect your funds and personal data. Adhering to robust security practices can mitigate common risks associated with API key management.

  1. Keep your API Secret confidential: The API Secret is analogous to a password. Never hardcode it in your application, commit it to version control (e.g., Git), or expose it in client-side code. Use environment variables, a dedicated secrets management service (like AWS Secrets Manager or Google Secret Manager), or secure configuration files that are not publicly accessible.
  2. Implement IP Whitelisting: If Bitcambio offers IP whitelisting, enable it. This feature restricts API access to a predefined list of trusted IP addresses. Even if your API Key and Secret are compromised, they cannot be used from an unauthorized IP address. This significantly enhances security for server-side applications.
  3. Grant Least Privilege: When generating API keys, configure them with the minimum necessary permissions. For example, if your application only needs to read account balances, do not grant it permission to place orders or initiate withdrawals. This limits the damage if a key is compromised.
  4. Regularly Rotate API Keys: Periodically rotate your API keys (e.g., every 90 days). This practice reduces the window of opportunity for an attacker to exploit a compromised key. When rotating, generate a new key pair, update your application, and then revoke the old key.
  5. Monitor API Usage: Regularly review your API access logs for any unusual activity, such as requests from unexpected IP addresses, unusually high request volumes, or failed authentication attempts. Anomalies could indicate a security breach.
  6. Secure Your Development Environment: Ensure that the machines and networks used for development and deployment are secure. Use strong, unique passwords, enable multi-factor authentication (MFA) for all access points, and keep software updated to patch known vulnerabilities.
  7. Use HTTPS/TLS: Always ensure that all communication with the Bitcambio API occurs over HTTPS (TLS). This encrypts data in transit, protecting your requests and responses from eavesdropping. Most API clients handle this automatically, but it's good practice to verify. For more information on securing web communications, refer to Mozilla's guide to Transport Layer Security (TLS).
  8. Error Handling and Logging: Implement robust error handling in your application to catch and log authentication failures. However, be cautious not to log sensitive information like API Secrets in plain text. Use structured logging to easily identify and respond to security events.