• Stars
    star
    287
  • Rank 144,232 (Top 3 %)
  • Language
  • License
    The Unlicense
  • Created over 8 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

SHA256 HMAC in different languages (both hex & base64 encoding)

e.g. for webhook hashes


Example inputs:

Variable Value
key the shared secret key here
message the message to hash here

Reference outputs for example inputs above:

Type Hash
as hexit 4643978965ffcec6e6d73b36a39ae43ceb15f7ef8131b8307862ebc560e7f988
as base64 RkOXiWX/zsbm1zs2o5rkPOsV9++BMbgweGLrxWDn+Yg=

PHP

<?php

$key = 'the shared secret key here';
$message = 'the message to hash here';

// to lowercase hexits
hash_hmac('sha256', $message, $key);

// to base64
base64_encode(hash_hmac('sha256', $message, $key, true));

NodeJS

var crypto = require('crypto');

var key = 'the shared secret key here';
var message = 'the message to hash here';

var hash = crypto.createHmac('sha256', key).update(message);

// to lowercase hexits
hash.digest('hex');

// to base64
hash.digest('base64');

JavaScript ES6

Using the Web Crypto API, available in all modern browsers. [1]

const key = 'the shared secret key here';
const message = 'the message to hash here';

const getUtf8Bytes = str =>
  new Uint8Array(
    [...unescape(encodeURIComponent(str))].map(c => c.charCodeAt(0))
  );

const keyBytes = getUtf8Bytes(key);
const messageBytes = getUtf8Bytes(message);

const cryptoKey = await crypto.subtle.importKey(
  'raw', keyBytes, { name: 'HMAC', hash: 'SHA-256' },
  true, ['sign']
);
const sig = await crypto.subtle.sign('HMAC', cryptoKey, messageBytes);

// to lowercase hexits
[...new Uint8Array(sig)].map(b => b.toString(16).padStart(2, '0')).join('');

// to base64
btoa(String.fromCharCode(...new Uint8Array(sig)));

Ruby

require 'openssl'
require 'base64'

key = 'the shared secret key here'
message = 'the message to hash here'

# to lowercase hexits
OpenSSL::HMAC.hexdigest('sha256', key, message)

# to base64
Base64.encode64(OpenSSL::HMAC.digest('sha256', key, message))

Elixir

key = 'the shared secret key here'
message = 'the message to hash here'

signature = :crypto.hmac(:sha256, key, message)

# to lowercase hexits
Base.encode16(signature, case: :lower)

# to base64
Base.encode64(signature)

Go

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
)

func main() {
	secret := []byte("the shared secret key here")
	message := []byte("the message to hash here")
	
	hash := hmac.New(sha256.New, secret)
	hash.Write(message)
	
	// to lowercase hexits
	hex.EncodeToString(hash.Sum(nil))
	
	// to base64
	base64.StdEncoding.EncodeToString(hash.Sum(nil))
}

Python 2

import hashlib
import hmac
import base64

message = bytes('the message to hash here').encode('utf-8')
secret = bytes('the shared secret key here').encode('utf-8')

hash = hmac.new(secret, message, hashlib.sha256)

# to lowercase hexits
hash.hexdigest()

# to base64
base64.b64encode(hash.digest())

Python 3

import hashlib
import hmac
import base64

message = bytes('the message to hash here', 'utf-8')
secret = bytes('the shared secret key here', 'utf-8')

hash = hmac.new(secret, message, hashlib.sha256)

# to lowercase hexits
hash.hexdigest()

# to base64
base64.b64encode(hash.digest())

C#

using System;
using System.Security.Cryptography;
using System.Text;

class MainClass {
  public static void Main (string[] args) {
    string key = "the shared secret key here";
    string message = "the message to hash here";
    
    byte[] keyByte = new ASCIIEncoding().GetBytes(key);
    byte[] messageBytes = new ASCIIEncoding().GetBytes(message);
    
    byte[] hashmessage = new HMACSHA256(keyByte).ComputeHash(messageBytes);
    
    // to lowercase hexits
    String.Concat(Array.ConvertAll(hashmessage, x => x.ToString("x2")));
    
    // to base64
    Convert.ToBase64String(hashmessage);
  }
}

Java

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import javax.xml.bind.DatatypeConverter;

class Main {
  public static void main(String[] args) {
  	try {
	    String key = "the shared secret key here";
	    String message = "the message to hash here";
	    
	    Mac hasher = Mac.getInstance("HmacSHA256");
	    hasher.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
	    
	    byte[] hash = hasher.doFinal(message.getBytes());
	    
	    // to lowercase hexits
	    DatatypeConverter.printHexBinary(hash);
	    
	    // to base64
	    DatatypeConverter.printBase64Binary(hash);
  	}
  	catch (NoSuchAlgorithmException e) {}
  	catch (InvalidKeyException e) {}
  }
}

Rust

extern crate hmac;
extern crate sha2;
extern crate base64;
extern crate hex;

use sha2::Sha256;
use hmac::{Hmac, Mac};

fn main() {
    type HmacSha256 = Hmac<Sha256>;

    let secret = "the shared secret key here";
    let message = "the message to hash here";

    let mut mac = HmacSha256::new_varkey(secret.as_bytes()).unwrap();

    mac.input(message.as_bytes());

    let hash_message = mac.result().code();

    // to lowercase hexits
    hex::encode(&hash_message);

    // to base64
    base64::encode(&hash_message);
}

More Repositories

1

Handlebars-Helpers

A small collection of useful helpers for Handlebars.js
JavaScript
274
star
2

Singing-with-Sinatra

Project files for a Nettuts+ series on Sinatra
CSS
68
star
3

JustDeleteMe-iOS

iOS App for JustDeleteMe (written in Swift)
Swift
48
star
4

avatar-uploader

The image/avatar uploader you always dreamed of
JavaScript
42
star
5

backbone.viewmanager

JavaScript
38
star
6

TutsPlus-Downloader

Download all videos in a Tuts+ Course with one click
JavaScript
18
star
7

JSONx

JSONx is an IBM standard for representing JSON as XML
PHP
18
star
8

JSONx-for-Laravel

Add XML support to your JSON API with a single middleware
PHP
17
star
9

tutsplusmarkdown

Convert your GitHub Flavoured Markdown to HTML for the Tuts+ Network
Ruby
13
star
10

fuel-s3

FuelPHP package for Amazon S3
PHP
13
star
11

GTAV

GTA V Map
JavaScript
12
star
12

fuelbackbonepusher

Demo of FuelPHP, Backbone.js and Pusher
PHP
12
star
13

fuel-exposable-model

FuelPHP package to ease in exposing model properties on your API
PHP
12
star
14

ng-contacts-app

A small "for-fun" AngularJS app, written with a bunch of nice ES6 goodness
JavaScript
10
star
15

portsdegree

University of Portsmouth Degree Classification Calculator
JavaScript
7
star
16

dotfiles

There's no place like home.
Vim Script
7
star
17

InboxActions

Inbox actions for Gmail and any other compatible email client
PHP
7
star
18

Recall

A Nettuts+ project
Ruby
5
star
19

A-Look-at-Popcorn

A quick demonstration of Popcorn for Nettuts+
JavaScript
5
star
20

markdown.js-demo

JavaScript
5
star
21

fuel-cheddar

FuelPHP package for the CheddarGetter API
PHP
4
star
22

playing-with-react-and-redux

JavaScript
4
star
23

Landing-Page

My website during the second half of 2010
4
star
24

StatusBoard

GitHub powered status reports
JavaScript
4
star
25

babel-repl

REPL with Plugins. Lots to do.
JavaScript
4
star
26

speech

Playing with Speech Recognition in WebKit
JavaScript
4
star
27

wordpress-status-checker

A ruby script for checking the status of your WordPress sites
3
star
28

Tagme

Tags. All fancy-like.
JavaScript
3
star
29

fuel-zipencoding

A FuelPHP port of the CodeIgniter Zip Encoding class.
PHP
3
star
30

Jumplist

A bookmarking script for the Bash Shell.
3
star
31

danharper.me-2011-nanoc

My new web site for 2011. Running on the nanoc static-site generator. HTML5 & CSS3 goodness baked right in!
Ruby
2
star
32

Backbone-CSS3-Generator

Demo application
JavaScript
2
star
33

Vim

Mostly for my vimrc file
1
star
34

DTI

Parse ISO 8601 date, duration and interval strings into DateTime objects
PHP
1
star
35

mdedit

Plan is to create a localStorage-backed Markdown editor
JavaScript
1
star
36

ENTWA-Coursework

2013 Enterprise Web Applications Coursework (97.5%)
Java
1
star
37

VoiceJammer

JavaScript
1
star
38

webcam-pip

open webcam in PiP (useful for using Camo when screen recording; Quicktime's preview window doesn't work with Camo)
HTML
1
star
39

dh-clean

Possible new site design
JavaScript
1
star
40

fluxible-decorators-experiment

JavaScript
1
star
41

Mote

On a Mote of Dust
1
star
42

graphql-typescript-codegen

Generate GraphQL from your existing TypeScript codebase
TypeScript
1
star
43

dh2012

Slick new site for 2012 full of CSS3 animations
JavaScript
1
star
44

Stem

A simple fixtures library for PHP
PHP
1
star
45

fuel-pdfcrowd

FuelPHP package for the PDFCrowd API
PHP
1
star
46

AUFDW

JavaScript
1
star
47

bug-removing-NSWindowStyleMaskTitled

remove the NSWindowStyleMaskTitled after creation, and it no longer hit tests properly after resize...
Objective-C
1
star
48

vivaWP.com

Homepage for the upcoming vivaWP open-source WordPress framework
1
star