Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 views
in Technique[技术] by (71.8m points)

base64 - 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('
')

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...