Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 493
thyme Avatar asked Nov 01 '25 13:11

thyme


2 Answers

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

like image 186
Richard Heap Avatar answered Nov 04 '25 20:11

Richard Heap


Hey I'm late to Answer this question. But I think anyone can use this Answer. I use https://pub.dev/packages/crypto package

For that you can use

import 'dart:convert';
import 'package:crypto/crypto.dart';


message = 'blabla'
secret = 'DfeRt[...]=='

void main() {
  var key = utf8.encode(secret);
  var bytes = utf8.encode(message);

  var hmacSha256 = Hmac(sha256, key); // HMAC-SHA256
  var digest = hmacSha256.convert(bytes);

  print("HMAC digest as bytes: ${digest.bytes}");
  print("HMAC digest as hex string: $digest");
}

I think this will save codes and clean.

like image 28
Kasun Hasanga Avatar answered Nov 04 '25 18:11

Kasun Hasanga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!