Base64 Hashes using HMAC SHA256 – Java, Python

I was testing a Restful web services (API) which required the REST request must be singed with HMAC SHA256 signatures. The signature has to be in the form of Base64 hash.

Lets see how this can be done using Java language:

JAVA:

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Base64HashHmacSha256 {

	/**
	 * Generate Base64 Hash using HMAC SHA256.
	 * @param message
	 * @param secret
	 * @return
	 * @throws NoSuchAlgorithmException 
	 * @throws UnsupportedEncodingException 
	 * @throws InvalidKeyException 
	 */
	public static String generateBase64Hash(String clientId, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
		
		Mac sha256Hmac = Mac.getInstance("HmacSHA256");		
		SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
		sha256Hmac.init(secret_key);
		
		return Base64.encodeBase64String(sha256Hmac.doFinal(clientId.getBytes("UTF-8")));
	}
	
	public static void main(String[] args) {
		
		String clientId = "Welcome to Buzzform";
		String secret = "it's upto you";
		
		try {
		System.out.println(generateBase64Hash(clientId, secret));
		} catch (Exception e) {
			System.out.println("Something went wrong! Better start running in Debug!!");
		}
	}

Lets see how we can do using Python:

Python 2.7.5:

import hashlib
import hmac
import base64

clientId = bytes("Welcome To Buzzform").encode('utf-8')
secret = bytes("password").encode('utf-8')

base64signature = base64.b64encode(hmac.new(secret, clientId, digestmod=hashlib.sha256).digest())
print(base64signature)

Python 3.5:

import hashlib
import hmac
import base64

clientId = bytes('Welcome To Buzzform', 'utf-8')
secret = bytes('password', 'utf-8')

base64signature = base64.b64encode(hmac.new(secret, clientId, digestmod=hashlib.sha256).digest())
print(base64signature)

Leave a Reply

Your email address will not be published. Required fields are marked *