Skip to content

Instantly share code, notes, and snippets.

@treble37
Forked from jasny/sha256-hmac.md
Created June 9, 2021 21:45
Show Gist options
  • Save treble37/0c5f2665840cfc68e8d7029e744fcafc to your computer and use it in GitHub Desktop.
Save treble37/0c5f2665840cfc68e8d7029e744fcafc to your computer and use it in GitHub Desktop.
Hashing examples in different languages

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');

Ruby

require 'openssl'

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) {}
  }
}

Example inputs:

Variable Value
message the message to hash here

Reference outputs for example inputs above:

Type Hash
as hexit 983564913cd4151d38b1af858da66c653658fcacdc1866134e915b60aded1e78
as base64 mDVkkTzUFR04sa+FjaZsZTZY/KzcGGYTTpFbYK3tHng=

PHP

<?php

$message = 'the message to hash here';

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

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

NodeJS

var crypto = require('crypto');

var message = 'the message to hash here';

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

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

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

Ruby

require 'openssl'

message = 'the message to hash here'

# to lowercase hexits
OpenSSL::Digest::SHA256.hexdigest message

# to base64
OpenSSL::Digest::SHA256.base64digest message

Elixir

message = 'the message to hash here'

hash = :crypto.hash(:sha256, message)

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

# to base64
Base.encode64(hash)

Go

package main

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

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

Python 2

import hashlib
import base64

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

hash = hashlib.sha256(message)

# to lowercase hexits
hash.hexdigest()

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

Python 3

import hashlib
import base64

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

hash = hashlib.sha256(message)

# 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 message = "the message to hash here";
    byte[] messageBytes = new ASCIIEncoding().GetBytes(message);
    
    byte[] hashmessage = SHA256.Create().ComputeHash(messageBytes);
    
    // to lowercase hexits
    String.Concat(Array.ConvertAll(hashmessage, x => x.ToString("x2")));
    
    // to base64
    Convert.ToBase64String(hashmessage);
  }
}

Java

import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;

class Main {
  public static void main(String[] args) {
  	try {
	    String message = "the message to hash here";

      MessageDigest digest = MessageDigest.getInstance("SHA-256");
      
      byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));	    
	    
	    // to lowercase hexits
	    DatatypeConverter.printHexBinary(hash);
	    
	    // to base64
	    DatatypeConverter.printBase64Binary(hash);
  	}
  	catch (NoSuchAlgorithmException e) {}
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment