Skip to content

Instantly share code, notes, and snippets.

@jondanao
Created August 26, 2015 08:19
Show Gist options
  • Save jondanao/4bafdd93f21cc937ad9e to your computer and use it in GitHub Desktop.
Save jondanao/4bafdd93f21cc937ad9e to your computer and use it in GitHub Desktop.
Signing API Requests via HMAC

Signing API Requests via HMAC

Ingredients of Authenticated Request

  1. API Secret Key (aka Private Key)
  • API Access Key (aka Public Key)
  • API Endpoint
  • Timestamp
  • Signature
  • Custom Headers

Process of Authenticating a Request

  1. Concatenate API Endpoint [3] and Timestamp [4] to create a new string
  2. Create the Signature [5] by calculating the HMAC of this string using the API Secret [1]
  3. Make a request to this endpoint by attaching some parts to the Custom Headers [6]:
    • Magpie-Access-Key
    • Magpie-Signature
    • Magpie-Timestamp

Sample Request

curl -X GET \
     -H "Magpie-Access-Key: FGHIJ67890" \
     -H "Magpie-Signature: a968473cfe470d0df23d7911e76b" \
     -H "Magpie-Timestamp: 2015-01-02 01:02:03" \
     http://api.magpie.im/v1/customers/

Calculating the Signature

Python

import hashlib, hmac

def sign(secret_key, endpoint, timestamp):
    msg = '%s %s' % (endpoint, timestamp)
    digest = hmac.new(secret_key, msg, hashlib.sha256).hexdigest()
    return digest

secret_key = 'ABCDE12345'
endpoint = '/v1/customers/'
timestamp = '2015-01-02 01:02:03'
signature = sign(secret_key, endpoint, timestamp)

Java

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public String sign(String secret, String endpoint, String timestamp){
    String message = endpoint + " " + timestamp;
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256"));
    String digest = new String(Hex.encodeHex(mac.doFinal(message.getBytes())));
    return digest
}

Objective-C

#import <IGDigest/NSString+SHA256HMAC.h>

- (NSString *)signatureWithSecret:(NSString *)secret endpoint:(NSString *)endpoint timestamp:(NSDate *)timestamp
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

    NSString *timestampFormatted = [dateFormatter stringFromDate:timestamp];
    NSString *message = [NSString stringWithFormat:@"%@ %@", endpoint, timestampFormatted];
    NSString *digest = [message SHA256HMACWithKey:secret];

    return digest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment