HMAC-SHA1

Bash

The openssl package available in most linux distributions include a way of creating the HMAC-SHA1 string from the command line…
1
echo -n "string to sign" | openssl dgst -sha1 -hmac "my secret key"
2
(stdin)= a993876ea1218921a1c8551923473da7b310dfae
Copied!

C\

1
Encoding encoding = Encoding.UTF8;
2
byte[] secretBytes = encoding.GetBytes(“my secret key”);
3
HMACSHA1 hmacsha1 = new HMACSHA1(secretBytes);
4
hmacsha1.ComputeHash(encoding.GetBytes(“string to sign”));
5
byte[] data = hmacsha1.Hash;
Copied!

Javascript

Cryptographic functions are available from the CryptJS libaray at https://code.google.com/p/crypto-js/.
1
var stringToSign = “string to sign”;
2
var secret = “my secret key”;
3
var signature = CryptoJS.HmacSHA1(stringToSign, secret);
Copied!

NodeJS

This code assumes you have the crypto-js library installed (npm install crypto-js)
1
$ cat hmacsha1.js
2
var CryptoJS = require('crypto-js'),
3
message = "string to sign",
4
secret = "my secret key",
5
sig = CryptoJS.HmacSHA1(message, secret);
6
console.log("" + sig);
7
8
$ node hmacsha1.js
9
a993876ea1218921a1c8551923473da7b310dfae
Copied!

Objective-C

HMAC-SHA1 functionality can be be included in IOS code by first adding the CommonCrypto library to your target, and including the following function in your appDelegate (or appropriate class)
1
#import <CommonCrypto/CommonDigest.h>
2
...
3
+(NSString*) hmac_sha1:(NSString*)input usingSecret:(NSString*)key
4
{
5
const char *cKey = [key UTF8String];
6
const char *cInput = [input UTF8String];
7
unsigned char digest[CC_SHA1_DIGEST_LENGTH];
8
if (cKey == nil || cInput == nil) {
9
return @"";
10
}
11
NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
12
CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cInput, strlen(cInput), digest);
13
for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
14
[output appendFormat:@"%02x", digest[i]];
15
}
16
return output;
17
}
18
...
Copied!

PHP

Generating the HMAC-SHA1 in PHP can be done using the following code.
1
<?php
2
$stringToSign = “string to sign”;
3
$keySecret = “my secret key”;
4
$signature = hash_hmac(”sha1”, $stringToSign, $keySecret);
5
echo $signature;
6
?>
Copied!
This will generate an encrypted hash of the string. In this case the string will be
a993876ea1218921a1c8551923473da7b310dfae

Ruby

Start up the ‘irb’ and try the following
1
irb(main):001:0> require('openssl')
2
=> true
3
irb(main):002:0> OpenSSL::HMAC.hexdigest('sha1', 'my secret key', 'string to sign')
4
=> "a993876ea1218921a1c8551923473da7b310dfae"
Copied!