Search code examples
dartbase64sha256hmac

Signing a message with hmac and sha256 in dart


I try to generate a sha256 HMAC using a base64-decoded secret key on a message. I would like to use the dart language. In python, I could do it with the following code:

# PYTHON CODE
import hmac, hashlib, base64
...
message = 'blabla'
secret = 'DfeRt[...]=='
secret_b64 = base64.b64decode(secret)
signature = hmac.new(secret_b64, message, hashlib.sha256)
signature_b64 = signature.digest().encode('base64').rstrip('\n')

Here is what I tried with dart:

// DART CODE
import 'package:crypto/crypto.dart';
import 'dart:convert';
...
String message = 'blabla';
String secret = 'DfeRt[...]=='
var secret_b64 = BASE64.decode(secret);
var hmac = new Hmac(sha256, secret_b64);
// what now?

But then I don't know how to go on. I found some old example code which looks like the following

var message_byte = UTF8.encode(message);
hmac.add(message_byte);

However, the method "add" does not exist any more in the Hmac class. I also tried this, but I am not sure if this is correct

var message_byte = UTF8.encode(message);    
var signature = hmac.convert(message_byte);
var signature_b64 = BASE64.encode(signature.bytes);

Can someone help me out?


Solution

  • If you have the whole 'message' available then just call convert(). If the message is large or in pieces then deal with it in chunks.

    Your example is simple, when spelled out step by step.

      String base64Key = 'DfeRt...';
      String message = 'blabla';
    
      List<int> messageBytes = utf8.encode(message);
      List<int> key = base64.decode(base64Key);
      Hmac hmac = new Hmac(sha256, key);
      Digest digest = hmac.convert(messageBytes);
    
      String base64Mac = base64.encode(digest.bytes);
    

    Please read the Effective Dart guide. Note how constants are now lower case, variables in Dart use camel case, etc