Page tree
Skip to end of metadata
Go to start of metadata

Assuming our helpdesk is located at http://acme.com/helpdesk, our API key is apikey, our secret key is secretkey:

PHP example

<?php

   $apiKey = "apikey";

   $secretKey = "secretkey";

   // Generates a random string of ten digits
   $salt = mt_rand();

   // Computes the signature by hashing the salt with the secret key as the key
   $signature = hash_hmac('sha256', $salt, $secretKey, true);

   // base64 encode...
   $encodedSignature = base64_encode($signature);

   // urlencode...
   $encodedSignature = urlencode($encodedSignature);

   echo "Voila! A signature: " . $encodedSignature;

?>

C# example

namespace KayakoIntegration
{
    class Program
    {

        static void Main()
        {
            var apiKey = "apikey";
            var secretKey = "secretkey";

            // Generate a new globally unique identifier for the salt
            var salt = System.Guid.NewGuid().ToString();

            // Initialize the keyed hash object using the secret key as the key
            HMACSHA256 hashObject = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));

            // Computes the signature by hashing the salt with the secret key as the key
            var signature = hashObject.ComputeHash(Encoding.UTF8.GetBytes(salt));

            // Base 64 Encode
            var encodedSignature = Convert.ToBase64String(signature);

            // URLEncode
            encodedSignature = System.Web.HttpUtility.UrlEncode(encodedSignature);

            Console.WriteLine("Voila! A signature: " + encodedSignature);

            Console.ReadKey();

        }
    }
}

VB.net example

Imports System.Security.Cryptography
Imports System.Text

Namespace KayakoIntegration
    Class Program

        Private Shared Sub Main()
            Dim apiKey = "apiKey"
            Dim secretKey = "secretkey"

            ' Generate a new globally unique identifier for the salt
            Dim salt = System.Guid.NewGuid().ToString()

            ' Initialize the keyed hash object using the secret key as the key
            Dim hashObject As New HMACSHA256(Encoding.UTF8.GetBytes(secretKey))

            ' Computes the signature by hashing the salt with the secret key as the key
            Dim signature = hashObject.ComputeHash(Encoding.UTF8.GetBytes(salt))

            ' Base 64 Encode
            Dim encodedSignature = Convert.ToBase64String(signature)

            ' URLEncode
            encodedSignature = System.Web.HttpUtility.UrlEncode(encodedSignature)

            Console.WriteLine("Voila! A signature: " & encodedSignature)

            Console.ReadKey()

        End Sub
    End Class
End Namespace

Ruby example

# Required Libraries
require 'openssl'
require 'base64'
require 'URI'

api_key = "apikey"
secret_key = "secretkey"

# URL encode
def urlncode(string)
URI.escape(string, Regexp.new("[Generating an API Signature^#{URI::PATTERN::UNRESERVED}]"))
end

# Generates a random string salt
salt = rand(10000000000).to_s


# Computes the signature by hashing the salt with the secret key as the key
hash = OpenSSL::HMAC.digest('sha256', secret_key, salt)

# base64 encode...
signature = urlncode(Base64.encode64(hash));

Python example

import hashlib
import random
import base64
import urllib
import hmac

apikey = "apikey"
secretkey = "secretkey"

# Generates a random string of ten digits
salt = str(random.getrandbits(32))

# Computes the signature by hashing the salt with the secret key as the key
signature = hmac.new(secretkey, msg=salt, digestmod=hashlib.sha256).digest()

# base64 encode...
encodedSignature = base64.encodestring(signature).replace('\n', '')

# urlencode...
encodedSignature = urllib.quote(encodedSignature)

print "Voila! A signature: " + encodedSignature

Java Example

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;

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

import org.bouncycastle.util.encoders.Base64Encoder;

public class Kayakoapi {

    public static void main(String[] args) throws GeneralSecurityException, IOException {

        String secretKey = "secretKey";
        String salt = "0123456789";

        String generateHmacSHA256Signature = generateHmacSHA256Signature(salt, secretKey);
        System.out.println("Signature: " + generateHmacSHA256Signature);

        String urlEncodedSign = URLEncoder.encode(generateHmacSHA256Signature, "UTF-8");

        System.out.println("Url encoded value: " + urlEncodedSign);
    }

    public static String generateHmacSHA256Signature(String data, String key) throws GeneralSecurityException {
        byte[] hmacData = null;

        try {
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(secretKey);
            hmacData = mac.doFinal(data.getBytes("UTF-8"));
            return new Base64Encoder().encode(hmacData);
        } catch (UnsupportedEncodingException e) {
            throw new GeneralSecurityException(e);
        }
    }
}

Cocoa (iOS and Mac)

-(NSUInteger)GenerateSalt
{
    // random number (change the modulus to the length you'd like)
    NSUInteger r = arc4random() % 100000;
    return r;
}

-(NSString *)GenerateSignatureUsingSalt:(NSUInteger)salt
{
    /*
     Make sure you import:
     #import <CommonCrypto/CommonHMAC.h>
     */

    NSString *key = SECRET_KEY;                                        // define your Secret Key string
    NSString *data = [NSString stringWithFormat:@"%u", salt];        // convert your random number

    const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];

    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];

    // Hash the salt with the secret key
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

    // Create a data structure
    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                          length:sizeof(cHMAC)];

    // Base64-encode the signature
    NSString *hash = [HMAC base64Encoding];

    // URL-encode the signature
    NSString * signatureURL = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                   (CFStringRef)hash,
                                                                                   NULL,
                                                                                   (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                   kCFStringEncodingUTF8 );

    return signatureURL;

}
  • No labels